Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 FormBuilder: Using 'this' in a custom validator

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]
       })
   }
}
like image 694
Vingtoft Avatar asked Oct 30 '16 14:10

Vingtoft


People also ask

What must be returned from a custom validator function?

The validator function needs to return null if no errors were found in the field value, meaning that the value is valid.

What must be returns from a custom validator function in Angular?

In the end, a custom validator is just a function that returns either an error object or null .

What methods should you implement for your custom validator?

Implementing the Validator Interface A Validator implementation must contain a constructor, a set of accessor methods for any attributes on the tag, and a validate method, which overrides the validate method of the Validator interface.


2 Answers

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

some_field: ['', [<any>Validators.required], c => this.customValidator(c)]
like image 139
JB Nizet Avatar answered Nov 10 '22 20:11

JB Nizet


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.

like image 24
Michael Oryl Avatar answered Nov 10 '22 18:11

Michael Oryl