Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save zihotki/e03b5fd9c14cd30e8045a5dd93f04bc5 to your computer and use it in GitHub Desktop.
Save zihotki/e03b5fd9c14cd30e8045a5dd93f04bc5 to your computer and use it in GitHub Desktop.
Angular 14+ async validator with de-bounce
employerCodeExists(): AsyncValidatorFn {
return (control: AbstractControl): Observable<ValidationErrors | null> => {
const hasEmployerCode = this.hasEmployerCodeFormControl.value;
const controlValue: string = control.value;
// Note: see https://stackoverflow.com/questions/36919011/how-to-add-debounce-time-to-an-async-validator-in-angular-2/62662296#62662296
// for explanation of why this is the most correct way to do async validation with debounce
if (hasEmployerCode && controlValue) {
return of(controlValue)
.pipe(
delay(200),
switchMap(employerCode => {
return this.personalDetailsService.getEmployerName(employerCode)
.pipe(
indicateLoading(this.isEmployerNameLoading$),
map(result => {
this.employerNameSubject.next(result);
return result === null ? {'employer-code-non-existant': true} : null;
})
);
})
)
} else {
return of(null);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment