Angular2 FormBuilder:在自定义验证器中使用“this" [英] Angular2 FormBuilder: Using 'this' in a custom validator
本文介绍了Angular2 FormBuilder:在自定义验证器中使用“this"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用 Angular2 的 FormBuilder 和自定义验证开发表单.问题:在 customValidator 中,我使用 this
来访问本地对象 data
.执行验证时出现 undefined
错误.
I'm developing a form using Angular2's FormBuilder with custom validation.
Problem: In customValidator I'm using this
to access the local object data
. I'm getting a undefined
error when the validation is executed.
看起来 customValidator 是在不同的对象中执行的,因此更改了 this
引用
It looks like the customValidator is executed in a different object and therefore changing the this
reference
问题:如何将 this
的引用传递给 customValidator?
Question: How can I pass a reference of this
to the 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]
})
}
}
推荐答案
使用箭头函数,确保函数绑定到这个:
Using an arrow function, to make sure the function is bound to this:
some_field: ['', [<any>Validators.required], c => this.customValidator(c)]
这篇关于Angular2 FormBuilder:在自定义验证器中使用“this"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文