Skip to main content

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>