3

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.

4

1 に答える 1

6

以下を使用できます。

HTML テンプレート: [(ngModel)]="myModel" #model (change)="changeEvent(model.value)"

Javascript ハンドラ:

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

コンソールには次のように記録されます。

<newValue>, <oldValue>

于 2016-12-26T21:59:26.370 に答える