angulartypescriptangular-forms

Angular FormControl with async validator stays in pending status


I have a Form which is not working correctly when I add an Async Validator without Sync validators.

When I add the async validator together with the sync validators the form works

name: new FormControl(
            '',
            Validators.required,
            this.validate.bind(this)
          ),

but when I remove the sync validator the form no longer works i.e other required controls are not triggering

 name: new FormControl(
                '',
                null,
                this.validate.bind(this)
              ),

here is the validate fn

 private validate(control:AbstractControl):Observable<ValidationErrors> {
return control.valueChanges.pipe(
      debounceTime(500),
      distinctUntilChanged(),

      switchMap((value: boolean) => {
        //some logic
        return of(null);
}

Please not that using first() and take(1) as suggested in some posts is not working . When I add a Validator.required on the sync validators everything works


Solution

  • I was able to fix this after following this thread https://github.com/angular/angular/issues/13200

    The solution included returning a null observable when the control is prestine or does not have valueChanges using take(1) to ensure that the returned observable in validate() fn is finite.

        private validate(control:AbstractControl):Observable<ValidationErrors> {
         if (!control.valueChanges || control.pristine) {
              return of(null);
            } else {
        return control.valueChanges.pipe(
              debounceTime(500),
              distinctUntilChanged(),
              take(1),
              switchMap((value: boolean) => {
                //some logic
                return of(null);
        },
    }