如何在角度2中使用ng-change事件?每当更改ng-model变量时,都必须调用一个函数。
[(ngModel)]="variable"
ngchange=variable;
答案 0 :(得分:70)
您可以使用ngModelChange
事件:
[(ngModel)]="variable" (ngModelChange)="doSomething($event)"
修改强>
根据您的评论,我认为您应该使用带有自定义验证器的表单控件。
以下是一个示例:
@Component({
(...)
template: `
<input [(ngModel)]="variable" [ngFormControl]="ctrl"/>
`
})
export class SomeComponent {
constructor() {
this.ctrl = new Control('', (control) => {
// validate the value
});
this.ctrl.valueChanges.subscribe((value) => {
// called when the value is updated
});
}
}
有关详细信息,请参阅此文章:
答案 1 :(得分:8)
组件具有双向绑定
这意味着你可以使用==&gt; [value] =&#34;变量&#34;(输入)=&#34; setVariable($ event)&#34;
event.target.value
FYI ==&GT; https://angular.io/docs/ts/latest/guide/user-input.html