Angular forms and routing · Build it
Build cross-field and async validators
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe interviewer asks
On a signup form, write a validator that checks 'confirm password' matches 'password', and an async validator that checks whether the username is taken by calling /api/users/exists. Show the error messages in the template.
Then
Follow-ups the interviewer asks next
- Why put the match check on the group and not on the confirm control?
- The async validator sends a request on every key press. How do you fix that?
- What's the form's status while the check runs?
- How would this look in signal forms?
- How do you test a validator?
The answer
What a strong answer covers
- Cross-field
ValidatorFnon the group:(g: AbstractControl): ValidationErrors | null => g.get('password')?.value === g.get('confirm')?.value ? null : { mismatch: true }, set with{ validators: passwordsMatch }. - Async: an
AsyncValidatorFnfactory that takes the API, e.g.usernameFree(api)returningc => timer(400).pipe(switchMap(() => api.exists(c.value)), map(taken => taken ? { taken: true } : null), catchError(() => of(null))). Angular cancels the previous check when the value changes, so thetimeracts as a debounce.updateOn: 'blur'is another option. - Status is
PENDINGwhile it runs; disable submit whileform.pending. - Template:
@if (form.hasError('mismatch') && form.controls.confirm.touched) { … }. - Signal forms: a
validate(...)rule that reads the other field, andvalidateHttpwith thedebounceoption (v22). - Validators are plain functions: test them with a
FormControlorFormGroup, no TestBed. - The server still checks at submit; the async check is only for user experience.
The red pen
Common traps
Avoid:an async validator with no debounce; the mismatch error shown on the wrong field; forgetting to return null when valid.
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voicePractise questions like this out loud
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.