简体   繁体   中英

Angular input events not triggered with ngModel binding

I am currently working on a small angular project and have a problem with input events.

I have following code:

<select (change)="onSelect($event.target.value)" >   
    <option *ngFor="let option of options" [value]="option.id">{{option.name}}</option> 
</select>

This is working fine and well. But I wanted to change it to following:

<select (change)="onSelect($event.target.value)" [(ngModel)]="selectedItem">
    <option *ngFor="let option of options" [value]="option.id">{{option.name}}</option>
</select>

Now after this the change event is not triggered anymore. I also tried [ngModel] and (ngModelChange) and a lot more. But as long as there is something with ngModel and a binding in it the events do not trigger anymore.

All my Angular stuff is in version 5.1.2, the CLI in 1.6.2

Does anyone know why Angular has that behaviour? Greetings and thank you.

it could work like this:

<select type="number" [(ngModel)]="selectedItem" >
  <option *ngFor="let option of options" [ngValue]="option.id">{{option.name}}</option>
</select>

Here is working plnkr hope it solve your issue bro :)

You should use ngModelChange when you are binding value using ngModel

<select (ngModelChange)="onSelect($event.target.value)" [(ngModel)]="selectedItem">
    <option *ngFor="let option of options" [value]="option.id">{{option.name}}</option>
</select>

You can try this:

<select type="number" [(ngModel)]="selectedItem" >
  <option *ngFor="let option of options" (click)=“selectedItem(option)” [ngValue]="option.id">{{option.name}}</option>
</select>

In component.ts -

optionSelected: any;
selectedItem(option: any) {
if (option) {
 this.optionSelected = option;
} else { 
 this.optionSelected = ‘’;
}
}

Then you can use this.optionSelected according to your need..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM