Created
August 21, 2023 11:39
-
-
Save zihotki/e03b5fd9c14cd30e8045a5dd93f04bc5 to your computer and use it in GitHub Desktop.
Angular 14+ async validator with de-bounce
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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