Angular 2 change event - model changes

Angular

Angular Problem Overview


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
}

Angular Solutions


Solution 1 - Angular

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

Solution 2 - Angular

If this helps you,

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

mychange(val)
{
   console.log(val); // updated value
}

Solution 3 - Angular

This worked for me

<input 
  (input)="$event.target.value = toSnakeCase($event.target.value)"
  [(ngModel)]="table.name" />

In Typescript

toSnakeCase(value: string) {
  if (value) {
    return value.toLowerCase().replace(/[\W_]+/g, "");
  }
}

Solution 4 - Angular

Use the (ngModelChange) event to detect changes on the model

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondanielView Question on Stackoverflow
Solution 1 - AngularGünter ZöchbauerView Answer on Stackoverflow
Solution 2 - AngularmicronyksView Answer on Stackoverflow
Solution 3 - AngularabasarView Answer on Stackoverflow
Solution 4 - AngulardeanwilliammillsView Answer on Stackoverflow