Angular2 FormBuilder: Using 'this' in a cu

2020-02-14 06:02发布

问题:

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.

It looks like the customValidator is executed in a different object and therefore changing the this reference

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]
       })
   }
}

回答1:

Using an arrow function, to make sure the function is bound to this:

some_field: ['', [<any>Validators.required], c => this.customValidator(c)]


回答2:

The accepted answer didn't work for me in Angular 2.0 due to typing issues (casting an AbstractControl to a FormControl, I believe). The following, however, solved the problem quite nicely:

ngOnInit() {
    this.myForm = this._fb.group({
        some_field: ['', [<any>Validators.required], this.customValidator.bind(this)]
    });
}

Using the .bind(this) on the reference to the validator did the trick for me.