ngModel
入力フィールドが変更された場合、Angular2 コンポーネントでコードを実行したいと考えています。(input)
イベントはあらゆるタイプのユーザー操作で発生するため、イベントをリッスンしたいと思います。(change)
これは、ここでイベントを使用できないことを意味します。値が変更された場合にのみコードを実行したい。
コンポーネントの例を次に示します。
import { Component } from '@angular/core';
@Component({
selector: 'myCuteComponent',
templateUrl: `
<h1>yoO World</h1>
<input [(ngModel)]="cuteValue" (input)="onInput($event)">
`
})
export class MyCuteComponent {
cuteValue = '';
constructor() { }
onInput(event) {
if (event.target.value !== this.cuteValue) {
console.log('value has changed'); // this will never run :(
}
}
}
問題は、起動event.target.value
時にすでに新しい値が含まれていることonInput
です。したがって、この方法は機能しませんconsole.log will
。決して実行されません。
質問:何らかのタイプのユーザー操作の後に値が実際に変更されたかどうかを検出するための適切な (そして一般的な) 解決策はありますか?