13
votes

How can I listen for changes on ngModel ? The problem: is that if i link (change) or (click) event to the element, in the given function when I access the model, its still not changed. If I add setTimeout of 500ms than I can the changed model. Any idea how can I get the real changed object without setTimeout which is very bad way ? Code in the html:

<input type="checkbox" (click)="autoJoinToggle()" [(ngModel)]='active.bookmark.autoJoin'> Autojoin

Code in the component:

 console.log(this.active.bookmark.autoJoin) // returns the current value (before the change)
 setTimeout(() => {console.log(this.active.bookmark.autoJoin);}, 500); //returns the value after the change

I cannot do this with Angular Control because I need the model binded and the "active" object does not exist in first place, and if I want to update the value of the control after "active" is defined, I need to listen on changes on the "active" object (which changes overtime). The same problem is with local variable and @ViewChild -> I still need to know when "active" changes so I update the local variable too.

Here is a gif as well: enter image description here

1

1 Answers

13
votes
(ngModelChange)="doSomething($event)"

or

autoJoinToggle(cb){ this.active.bookmark.autoJoin = cb; //do something.. }

<input #cb type="checkbox" (click)="autoJoinToggle(cb.checked)" 
    [(ngModel)]='active.bookmark.autoJoin'>

I think the behavior you explain is a bug though and a pull request already provided but not added https://github.com/angular/angular/issues/6311.