Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 change event - model changes

Tags:

angular

How can I get the values after a model has changed? The (change) event does fire before the model change. I do not want to use event.target.value

<input type="checkbox"  (change)="mychange(event)" [(ngModel)]="mymodel">  public mychange(event) {    console.log(mymodel); // mymodel has the value before the change } 
like image 741
daniel Avatar asked Mar 22 '16 09:03

daniel


People also ask

What is the difference between ngModelChange and change?

ngModelChange It fires when the model changes. You cannot use this event without ngModel directive. change triggers when the user changes the input. ngModelChange triggers when the model changes, irrespective of that change is caused by the user or not.

What is ngModel change?

NgModelChange is an Angular specific event, which we can use to listen for changes to the user input. It is the @Output property of the ngModel directive, Hence we need to use it along with it. ngModle raises the NgModelChange event, whenever the model changes.

Can I use ngModelChange without ngModel?

The NgModel class has the update property with an EventEmitter instance bound to it. This means we can't use (ngModelChange) without ngModel .

How do I update my ngModel value?

If we use two way binding syntax for ngModel the value will be updated. So the default (ngModelChange) function will update the value of ngModel property. i.e., user.Name . And the second (ngModelChange) will be triggered printing the user name value in the console.


1 Answers

That's a known issue. Currently you have to use a workaround like shown in your question.

This is working as intended. When the change event is emitted ngModelChange (the (...) part of [(ngModel)] hasn't updated the bound model yet:

<input type="checkbox"  (ngModelChange)="myModel=$event" [ngModel]="mymodel"> 

See also

  • https://github.com/angular/angular/issues/3406,
  • https://github.com/angular/angular/issues/6311
like image 155
Günter Zöchbauer Avatar answered Sep 24 '22 06:09

Günter Zöchbauer