63

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
}
daniel
  • 34,281
  • 39
  • 104
  • 158
  • 1
    Possible duplicate of [Angular 2 not giving current state of checkbox](http://stackoverflow.com/questions/34872843/angular-2-not-giving-current-state-of-checkbox) – Günter Zöchbauer Mar 22 '16 at 09:08

4 Answers4

59

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

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • 1
    Note that Gunter uses `(ngModelChange)` wrapped in parentheses -- not just `ngModelChange` – Nate Anderson Jan 24 '17 at 00:52
  • Too bad that `ngModelChange` is now deprecated. [Check it here](https://github.com/angular/angular/blob/master/packages/forms/src/directives/reactive_directives/form_control_name.ts) – Mateut Alin Feb 15 '19 at 10:07
  • 2
    Thats just a property from `FormControlName` directive https://github.com/angular/angular/blob/master/packages/forms/src/directives/reactive_directives/form_control_name.ts#L128 The `ngModelChange` from `NgModel` is not deprecated https://github.com/angular/angular/blob/master/packages/forms/src/directives/ng_model.ts#L193 – Günter Zöchbauer Feb 15 '19 at 10:10
  • 2
    @MTZ I think that `ngModelChange` is only deprecated in reactive forms and not in template-driven forms. – Caltor Feb 12 '20 at 12:00
  • The workaround I ussualy use is setTimeout(()=>{ ... read updated model...},0) – assassinatorr Aug 06 '20 at 13:23
52

If this helps you,

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

mychange(val)
{
   console.log(val); // updated value
}
micronyks
  • 54,797
  • 15
  • 112
  • 146
  • This answer is helpful, but I can see why Gunter's was the chosen answer, because he points out that `(change)` is different, as said in his github issues; "click is a DOM event, not related to the higher level ngModel. The proper event for this is ngModelChange." – Nate Anderson Jan 24 '17 at 03:07
4

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, "");
  }
}
adiga
  • 34,372
  • 9
  • 61
  • 83
abasar
  • 1,659
  • 1
  • 12
  • 7
2

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

deanwilliammills
  • 2,617
  • 2
  • 21
  • 27