0

I would like to get the selected value of a select option in Angular 7. Two-way data binding using ngModel and I also imported FormsModule in app.module.ts.

My HTML file:

<select (change)="selectChangeHandler($event)" 
[(ngModel)]="optSelected"> 
 <option *ngFor="let opt of options" [value]="opt.id"> 
{{opt.title}} 
</option> 
</select>

My TS file:

optSelected = 'aaa';
selectChangeHandler(event: any) {
  this.optSelected = event.target.value;
  console.log('The selected option is: ' + this.optSelected);
}
Alex94
  • 65
  • 2
  • 10
  • Possible duplicate for: https://stackoverflow.com/questions/46447459/get-value-from-select-option-in-angular-4 – Hunor May 30 '19 at 09:18

1 Answers1

2

Since you are using ngModel/two-way data binding, instead of using the change event, you can simply make use of the ngModelChange event binding. According to the documentation, it is the

Event emitter for producing the ngModelChange event after the view model updates.

<select (ngModelChange)="selectChangeHandler($event)" [(ngModel)]="optSelected"> 
  <option *ngFor="let opt of options" [value]="opt.id"> 
    {{opt.title}} 
  </option> 
</select>

And on your component.ts,

selectChangeHandler() {
  console.log(this.optSelected);
}
wentjun
  • 40,384
  • 10
  • 95
  • 107