[英]Detecting changes to a model within the same component - Angular
我知道我們可以使用帶有 onChange 鈎子的 @Input 來檢測子組件中父組件中所做的更改。 但我的用例是檢測對同一組件內的模型所做的更改。 組件.ts:
export class MyComponent implements OnInit {
private myExmapleModel: MyModel;
ngOnInit: void {
this.momyExmapleModeldel = new MyModel('', '', '');
}
}
我以兩種方式將此 myExampleModel 綁定到模板 html,並希望在同一個 MyComponent 中 MyModel 實例中的值發生更改時觸發一個函數。 我怎樣才能做到這一點?
如果您像這樣在 html 中使用myExmapleModel
:
<input ([ngModel])="myExmapleModel">
您可以像這樣使用ngModelChange
回調:
<input [ngModel]="myExmapleModel" (ngModelChange)="onChange($event)"
如果要檢測輸入的變化,請使用 input-event 或要檢測焦點的變化,即光標不在輸入框中,請使用 change-event
<input [(ngModel)]="name" (input)="changed()" />
<input [(ngModel)]="name" (change)="changed()" />
changed() {
console.log('name changed')
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.