Angular 2 ngModel compare old and new value

8.6k Views Asked by At

So I've been playing around with Angular 2 for a while now. Using the [(ngModel)] directive in an <input> is pretty simply. Yet I can't figure out how to pass or at least get the previous value so I can compare both - the new and old one.

I'm getting the change detection through (ngModelChange) since (change) fired up after bluring out of the input field (seems to be a bug btw). So my code currently looks like this ($event could be seen as a placeholder, since I've no idea what to pass in).

<input [(ngModel)]="myModel" (ngModelChange)="changeEvent($event)">

I've also tried passing in a custom local template variable like so, which obviously didn't work as well:

<input [(ngModel)]="myModel" #myModel="ngModel" (ngModelChange)="changeEvent($event)">

I know, there's at least a possibility to achieve this by using DoCheck. But since I just need that for a single time (currently) I really don't want to use that method. On top of that I'm using the above construct inside of an *ngFor.

1

There are 1 best solutions below

4
On

You can use the following:

HTML Template: [(ngModel)]="myModel" #model (change)="changeEvent(model.value)"

Javascript handler:

changeEvent(newValue) {
  console.log(newValue, this.myModel);
}

The console will log:

<newValue>, <oldValue>