Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 listen on model change

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

like image 936
Denko Mancheski Avatar asked Feb 18 '16 12:02

Denko Mancheski


People also ask

How do you check ngModel value is changed or not?

The (ngModelChange)=”modelChangeFn($event)” will fire before the value bound to [(ngModel)] has changed.

Can I use NgModelChange without ngModel?

We can't use mgModelChange without ngModel because the ngModel class has update function with EventEmitter instance.

What is the use of NgModelChange in angular?

AngularJS ng-change Directive The ng-change directive tells AngularJS what to do when the value of an HTML element changes. The ng-change directive requires a ng-model directive to be present.


1 Answers

(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.

like image 85
Günter Zöchbauer Avatar answered Oct 12 '22 01:10

Günter Zöchbauer