2
votes

Sorry for my bad english.

I'm trying to use a custom async validation in my angular application like this

 asyncValidator(control:FormControl):Promise<any>{
    const promise = new Promise<any>(
      (resolve, reject) =>{
        setTimeout(() => {
          console.log("it works");
          resolve(null);
        },5000);
      }
    );
    return promise;
  }

I declared my reactive form like this:

this.customForm = this.formbuilder.group({
      'userData': this.formbuilder.group({
        'name': ['',this.asyncValidator],
        'email': [''],
      }),
      'pass': [''],
      'gender': ['male'],
      'hobbies': this.formbuilder.array([
        ['Reading']
      ])
    })

Even though, the asyncValidator always resolve(null), the name input still has ng-invalid class.

enter image description here

1

1 Answers

1
votes

You incorrectly placed your async validator.

It should be:

'name': ['', null, this.asyncValidator],
         (1)  (2)          (3)      

where:

(1) - control value

(2) - sync validator

(3) - async validator

Stackblitz example