我正在使用带有自定义验证的Angular2的FormBuilder开发表单。问题:在customValidator中,我this
用来访问本地对象data
。undefined
执行验证时出现错误。
看起来customValidator是在其他对象中执行的,因此更改了this
引用
问题:如何传递this
对customValidator的引用?
export class Ast {
public data:any;
public myForm:FormGroup;
constructor(private _fb:FormBuilder) {
this.data = {foo: "bar"};
}
customValidator(c: FormControl) {
if (this.data.foo == "bar") { // This line crashes
// DO something
}
}
ngOnInit() {
this.myForm = this._fb.group({
some_field: ['', [<any>Validators.required], this.customValidator]
})
}
}
使用箭头函数,以确保该函数绑定到此:
some_field: ['', [<any>Validators.required], c => this.customValidator(c)]
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句