0

I have a dropdown menu and I want to change the dropdown value from the component file on button click

 <select
      id="currentPeriodDropDown"
      (change)="onCurrentSnapshotPeriodChange()"
      [(ngModel)]="currentSnapshotPeriod"
      class="form-control form-control-sm mr-1 form-control-sm-ipad"
    >
      <option [ngValue]="period" *ngFor="let period of snapshotPeriods"
        >{{ period?.periodName }}
      </option>
    </select>

I want to change the value from the component file without selecting the option from dropdown.

Giannis
  • 1,790
  • 1
  • 11
  • 29
  • Did you try setting the currentSnapshotPeriod? Please show your ts code. – Giannis Nov 14 '19 at 14:48
  • @Giannis yes that didnt work. So basically the current selected item will be replaced. So for ex if we have a,b,c,d and current selected item is b and then i select c and then i execute this code i get the dropdown value as a,b,b,d – taashibhulani Nov 14 '19 at 14:53
  • I am not sure what the expected result is. Please check https://stackoverflow.com/questions/35945001/binding-select-element-to-object-in-angular and provide a demo if you like. – Giannis Nov 14 '19 at 15:00

2 Answers2

0

Try the below code,

this.currentSnapshotPeriod = "some value"; /* This value should exist in option values*/
Gangadhar Gandi
  • 2,162
  • 12
  • 19
  • i tried this but it just changes the value of the dropdown and so there will be 2 items. So basically the current selected item will be replaced. So for ex if we have a,b,c,d and current selected item is b and then i select c and then i execute this code i get the dropdown value as a,b,b,d – taashibhulani Nov 14 '19 at 14:53
0

You need another variable there, and you set it empty. Then the display in the select is that variable if not empty, or the other one if it is. Example:

TS file:

var displayInSelect: string;

buttonClicked() {
   this.displayInSelect = 'Whatever You Want';
}

And then your HTML is:

    <select id="currentPeriodDropDown" 
      (change)="onCurrentSnapshotPeriodChange()" 
      [(ngModel)]="currentSnapshotPeriod" 
      class="form-control form-control-sm mr-1 form-control-sm-ipad">
        <option [ngValue]="period" *ngFor="let period of snapshotPeriods">
          {{ displayInSelect?displayInSelect:(period?.periodName) }}
        </option>
    </select>

And then the button (click) would call the function "buttonClicked"

Note that this won't change the option you selected, only the displayed value in the select

Antonio Ortells
  • 327
  • 2
  • 11