Angular2 FormBuilder:在自定义验证器中使用"this" [英] Angular2 FormBuilder: Using 'this' in a custom validator

查看:260
本文介绍了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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆