16
votes

I'm building an Angular 2 application (2.0) and I've got a form that makes use of the ReactiveForms module. As such, I'm using validator functions on the input fields, including custom validators. This works fine.

My issue is that I am also trying to use a custom AsyncValidator on a form field. It seems straight forward enough, but I can never reference properties inside the class from within the AsyncValidator method.

The FormGroup and the FormControl properties for the form itself and the input field look like this in the component's class:

form: FormGroup;
userName = new FormControl("", [Validators.required], [this.userNameAsyncValidator]);

There's also a FormBuilder in the ngOnInit() function that attaches the form to the form property.

constructor(private fb: FormBuilder, // this.fb comes from here
          private css: ClientSecurityService) { // this.css comes from here
}

ngOnInit() {
  this.form = this.fb.group({
      "userName": this.userName
    }
  );
}

My issue is that in the AsyncValidator, I am unable to reference any of the services I've defined in the component's class - including this.css. Here's the validator:

userNameAsyncValidator(control: FormControl): {[key: string]: any} {
  return new Promise(resolve => {
    this.css.getUrl()
      .subscribe(
        data => {
          console.log('Returned http data:', data);
          resolve(null);
        },
        err => {
          // Log errors if any
          console.log(err);
        });
  });
}

No matter what I do, this.css in the userNameAsyncValidator() call is undefined.

(I realize that my validator doesn't actually do anything - I just want to be able to call my ClientSecurity service so that I can, eventually, call a remote HTTP webservice to get a response as to whether the userName being entered is valid and not already in use.)

1
As you are using an arrow function, the problem is probably that the userNameAsyncValidator function isn't bound to the right this. Who invokes this function? How is this function passed? If you pass it then pass it like so: this.userNameAsyncValidator.bind(this) - Nitzan Tomer
@NitzanTomer It's a likely a class (prototype) method, which cannot be defined with an arrow function - Juan Mendes

1 Answers

41
votes

Your validator is not being called with your component as this. Notice that you are passing a loose reference to this.userNameAsyncValidator You can bind your validator without worrying about this conflicts because angular validation doesn't rely on this

userName = new FormControl("", [
    Validators.required
], [
    this.userNameAsyncValidator.bind(this)
]);