检测同一组件内模型的更改 - Angular
Detecting changes to a model within the same component - Angular
我知道我们可以使用带有 onChange 钩子的 @Input 来检测子组件中父组件中所做的更改。
但我的用例是检测同一组件内对模型所做的更改。
component.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 或者想检测 focus-away 的变化,即光标不在输入框中,使用 change-event
<input [(ngModel)]="name" (input)="changed()" />
<input [(ngModel)]="name" (change)="changed()" />
changed() {
console.log('name changed')
}
我知道我们可以使用带有 onChange 钩子的 @Input 来检测子组件中父组件中所做的更改。 但我的用例是检测同一组件内对模型所做的更改。 component.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 或者想检测 focus-away 的变化,即光标不在输入框中,使用 change-event
<input [(ngModel)]="name" (input)="changed()" />
<input [(ngModel)]="name" (change)="changed()" />
changed() {
console.log('name changed')
}