Vingtoft Vingtoft - 1 year ago 73
AngularJS Question

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

to access the local object
. I'm getting a
error when the validation is executed.

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

Question: How can I pass a reference of
to the customValidator?

export class Ast {
public data:any;
public myForm:FormGroup;

constructor(private _fb:FormBuilder) { = {foo: "bar"};

customValidator(c: FormControl) {
if ( == "bar") { // This line crashes
// DO something

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

Answer Source

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

some_field: ['', [<any>Validators.required], c => this.customValidator(c)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download