ChatGPT解决这个技术问题 Extra ChatGPT

Angular 2 change event - model changes

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
}

G
Günter Zöchbauer

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


Note that Gunter uses (ngModelChange) wrapped in parentheses -- not just ngModelChange
Too bad that ngModelChange is now deprecated. Check it here
Thats just a property from FormControlName directive github.com/angular/angular/blob/master/packages/forms/src/… The ngModelChange from NgModel is not deprecated github.com/angular/angular/blob/master/packages/forms/src/…
@MTZ I think that ngModelChange is only deprecated in reactive forms and not in template-driven forms.
The workaround I ussualy use is setTimeout(()=>{ ... read updated model...},0)
m
micronyks

If this helps you,

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

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

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."
a
adiga

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, "");
  }
}

d
deanwilliammills

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