我正在使用带有自定义验证的Angular2的FormBuilder开发表单。问题:在customValidator中,我this用来访问本地对象data。undefined执行验证时出现错误。
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)]