Lab 04: Async Validator
π Resourcesβ
π Starter Codeβ
step-4-album-wholesale-v16-post-add-custom-validator
In this lab, you'll build an asynchronous validator that checks if an album already exists by making HTTP requests. You'll use RxJS operators like debounceTime and switchMap to optimize the validation, and display loading states during async validation.
π Instructionsβ
Step 1: Create Async Validatorβ
Create an async validator that returns an Observable:
import { AsyncValidatorFn } from '@angular/forms';
import { map, debounceTime, switchMap } from 'rxjs/operators';
export function albumExistsValidator(albumService: AlbumService): AsyncValidatorFn {
return (control: AbstractControl) => {
if (!control.value) return of(null);
return of(null).pipe(
debounceTime(300),
switchMap(() => albumService.checkExists(control.value)),
map(exists => exists ? { albumExists: true } : null)
);
};
}
Step 2: Apply to FormControlβ
Add async validator as third parameter:
albumForm = this.fb.group({
name: ['', [Validators.required], [albumExistsValidator(this.albumService)]]
});
Step 3: Show Pending Stateβ
Display loading indicator:
<span *ngIf="albumForm.get('name')?.pending">
Checking...
</span>
<mat-error *ngIf="albumForm.get('name')?.errors?.['albumExists']">
Album already exists
</mat-error>