Angular 4:在自定义验证器函数中使用组件变量
Angular 4: using component variables inside custom validator functions
ngOnInit(): void {
this.formBuilder.group({
nameFormCtrl: ['', this.validateName],
});
}
validateName(c: FormControl) {
return c.value === this.name ? null : {
validateName: {
valid: false
}
};
}
这里this.name
应该是指组件,而不是指undefined
Class 方法没有 this
绑定到当前实例,它们依赖于调用者在调用时将适当的 this
传递给函数,就像任何其他方法一样function
在 Javascript
您可以使用从声明上下文捕获 this
的箭头函数,或使用 bind
:
显式绑定 this
this.formBuilder.group({
nameFormCtrl: ['', c=> this.validateName(c)],
// OR
nameFormCtrl: ['', this.validateName.bind(this)],
});
ngOnInit(): void {
this.formBuilder.group({
nameFormCtrl: ['', this.validateName],
});
}
validateName(c: FormControl) {
return c.value === this.name ? null : {
validateName: {
valid: false
}
};
}
这里this.name
应该是指组件,而不是指undefined
Class 方法没有 this
绑定到当前实例,它们依赖于调用者在调用时将适当的 this
传递给函数,就像任何其他方法一样function
在 Javascript
您可以使用从声明上下文捕获 this
的箭头函数,或使用 bind
:
this
this.formBuilder.group({
nameFormCtrl: ['', c=> this.validateName(c)],
// OR
nameFormCtrl: ['', this.validateName.bind(this)],
});