Detect change in ngModel on selected tag (Angular 2)

I am trying to detect a change to ngModel in a <select> . In Angular 1.x, we can solve this with $watch on ngModel or with ngChange , but I still haven't figured out how to detect a change in ngModel in Angular 2.

Example : http://plnkr.co/edit/9c9oKH1tjDDb67zdKmr9?p=info

As we see, if we select a different value from the drop-down list, our ngModel will change, and the interpolated expression in the view reflects this.

How do I get notified of this change in my class / controller?

+42
javascript angularjs angular
Dec 21 '15 at 10:20
source share
3 answers

Update

Separate event and property bindings:

 <select [ngModel]="selectedItem" (ngModelChange)="onChange($event)"> 
 onChange(newValue) { console.log(newValue); this.selectedItem = newValue; // don't forget to update the model here // ... do other stuff here ... } 

You can also use

 <select [(ngModel)]="selectedItem" (ngModelChange)="onChange($event)"> 

and then you will not need to update the model in the event handler, but I believe that this leads to two events, so this is probably less efficient.




Old answer before they fixed the bug in beta.1:

Create a local template variable and attach an event (change) :

 <select [(ngModel)]="selectedItem" #item (change)="onChange(item.value)"> 

plunker

See also How to get a new selection in "select" in Angular 2?

+115
Dec 21 '15 at 22:31
source share
— -

I came across this question and I will post my answer, which used and worked very well. I had a search box that also filtered arrays of objects, and in the search box I used (ngModelChange)="onChange($event)"

in my .html

 <input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search"> 

then in my component.ts

 reSearch(newValue: string) { //this.searchText would equal the new value //handle my filtering with the new value } 
+7
Apr 25 '16 at 21:26
source share

this does not really affect the change in the model; it detects any change event in the input field. For example, if the input field has the value "my_search_word" and you change it to "my_search_word_2" and then return to "my_search_word", the model value will not change in this case, but reSearch($event) still considers that there is a change.

-2
Sep 27 '16 at 16:40
source share



All Articles