Sub topic 5
Showing errors in the template
This chapter assumes you can write a validator function and attach it to a FormControl or FormGroup, as covered in the earlier chapters. It also assumes you know Angular control flow (@if, which needs Angular 17 or later) and basic template binding. The chapter covers what a template can read from a control, when to show an error, how to display error details, and how to handle group-level errors, pending async checks, and template-driven forms.
What the template can read
A validator only produces data. The template decides whether and how a user sees that data. Every AbstractControl exposes state you can bind to.
| Property | Meaning |
|---|---|
| `valid` | The control has no errors and is not pending or disabled. |
| `invalid` | Validation finished and at least one error exists. |
| `pending` | An async validator is still running. |
| `disabled` | The control is excluded from validation. Both `valid` and `invalid` are `false`. |
| `touched` | The user focused the control and then left it (a blur event). |
| `dirty` | The user changed the value through the UI. |
| `pristine` | The opposite of `dirty`. |
| `errors` | The merged `ValidationErrors` object, or `null` when there are none. |
Three methods read errors:
hasError(code, path?)returnstrueif the error key exists.getError(code, path?)returns the value stored under that key, ornull.- The
errorsproperty gives the whole object.
The path argument is optional. It lets you ask a parent group about a child control, for example form.hasError('required', 'name').
The basic pattern
Showing every error as soon as the page loads is hostile. An empty required field is invalid from the first render, but the user has not done anything wrong yet. The usual rule is to show errors only when the control is invalid and the user has interacted with it.
Here is the pattern for the name field built in earlier chapters:
<input id="name" type="text" [formControl]="form.controls.name" />
@if (form.controls.name.invalid && (form.controls.name.dirty || form.controls.name.touched)) {
@if (form.controls.name.hasError('required')) {
<p>Name is required.</p>
}
@if (form.controls.name.hasError('whitespace')) {
<p>Name cannot be only whitespace.</p>
}
}Each inner @if is independent, so several messages can appear at once. That is correct when the errors do not overlap. If a control has both required and whitespace errors, the user sees two messages for one mistake. In this particular case the validator from the earlier chapter returns null for an empty string, so only one fires. Check your own validators for overlap before you decide how to display them.
Reading error details
Error values can carry data. The factory from the earlier chapter returns { forbiddenName: { value } }, and the template can use that payload. getError returns it directly. Combine it with the as alias of @if:
@if (form.controls.name.getError('forbiddenName'); as error) {
<p>"{{ error.value }}" is not an allowed name.</p>
}The alias is only truthy when the error exists, so this block replaces a separate hasError check. Built-in validators also carry payloads. For example, Validators.minLength(3) produces { minlength: { requiredLength: 3, actualLength: 1 } }. Note the lowercase minlength key. Built-in keys do not always match the validator's method name, so check the key before you write the template.
If you read errors directly, remember that it can be null. Under strict template checking, write:
{{ form.controls.name.errors?.['forbiddenName']?.value }}The bracket access is required because ValidationErrors is an index-signature type, and the ?. protects against null.
Keeping the template short
The long condition above repeats for every field. Move it into the component:
import { Component } from '@angular/core';
import {
AbstractControl,
FormControl,
FormGroup,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { forbiddenNameValidator } from './forbidden-name.validator';
import { noWhitespaceValidator } from './no-whitespace.validator';
@Component({
selector: 'app-name-form',
standalone: true,
imports: [ReactiveFormsModule],
templateUrl: './name-form.component.html',
})
export class NameFormComponent {
readonly form = new FormGroup({
name: new FormControl('', {
nonNullable: true,
validators: [
Validators.required,
noWhitespaceValidator,
forbiddenNameValidator(['admin', 'root']),
],
}),
});
get name(): FormControl<string> {
return this.form.controls.name;
}
shouldShowErrors(control: AbstractControl): boolean {
return control.invalid && (control.dirty || control.touched);
}
onSubmit(): void {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
console.log(this.form.getRawValue());
}
}The matching template uses else if so only the first applicable message appears:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<label for="name">Name</label>
<input
id="name"
type="text"
formControlName="name"
[attr.aria-invalid]="shouldShowErrors(name)"
aria-describedby="name-errors"
/>
<div id="name-errors" role="alert">
@if (shouldShowErrors(name)) {
@if (name.hasError('required')) {
<p>Name is required.</p>
} @else if (name.hasError('whitespace')) {
<p>Name cannot be only whitespace.</p>
} @else if (name.getError('forbiddenName'); as error) {
<p>"{{ error.value }}" is not an allowed name.</p>
}
}
</div>
<button type="submit">Save</button>
</form>The order of the else if branches sets the priority of messages. Put the most basic problem first.
@let (Angular 18.1 and later) is an alternative to the getter. @let name = form.controls.name; declares a template variable you can use below it.
The submit handler calls markAllAsTouched(). Without it, a user who clicks Save on an untouched empty form sees nothing, because the controls are neither dirty nor touched. Marking everything touched makes the existing display rule reveal all errors at once.
The aria-invalid binding and role="alert" container let screen readers announce problems. The role="alert" region should exist in the DOM before its content changes, which is why the div sits outside the @if.
Errors on a group
A cross-field validator reports its error on the group, not on either field. Reading the field's errors will never find it.
<input id="password" type="password" formControlName="password" />
<input id="confirm" type="password" formControlName="confirm" />
@if (form.hasError('passwordsMismatch') && form.controls.confirm.touched) {
<p>Passwords do not match.</p>
}This assumes a FormGroup with password and confirm controls and passwordsMismatch registered as a group validator. Three details matter:
form.hasError('passwordsMismatch')checks the group's ownerrors. It does not look at children unless you pass a path.- Group error state changes whenever any child value changes. If you used only
form.dirty, the message would show up as soon as the user edited the first field. Gating onconfirm.touchedwaits until the user has finished with the second field. - A group is
invalidif it has its own errors or if any child is invalid. Soform.invaliddoes not tell you which one caused it. Test the specific key.
A group-level error also does not add the ng-invalid CSS class to the confirm input. If you style invalid inputs by class, bind a class yourself, for example [class.invalid]="form.hasError('passwordsMismatch') && form.controls.confirm.touched".
Pending async validation
While an async validator runs, the control status is PENDING. invalid is false during that time, and errors has no entry from the async validator. Without handling it, the user sees nothing until the server replies.
@if (form.controls.username.pending) {
<p>Checking availability…</p>
} @else if (form.controls.username.hasError('usernameTaken')) {
<p>That username is taken.</p>
}Angular runs async validators only after all synchronous validators on that control pass. A control with a required error never shows pending, and the service is never called. That is useful for avoiding wasted requests, but it means the pending message belongs to the case where the value already looks well-formed.
A form is not valid while a control is pending. If you disable the submit button with [disabled]="form.invalid", a pending control leaves the button enabled, because the form is neither valid nor invalid. Use [disabled]="!form.valid" when you want to block submission until every check has finished.
Template-driven forms
With ngModel there is no form.controls.name object in your class. Export the directive into a template reference variable instead:
<input
name="name"
[(ngModel)]="model.name"
required
appForbiddenName="admin"
#name="ngModel"
/>
@if (name.invalid && (name.dirty || name.touched)) {
@if (name.hasError('required')) {
<p>Name is required.</p>
}
@if (name.hasError('forbiddenName')) {
<p>That name is not allowed.</p>
}
}The #name="ngModel" reference gives you the same NgModel control API as in a reactive form, so the condition and the hasError calls are identical. A later chapter covers the directive that provides appForbiddenName. In this form, the attribute value admin would be bound as a string and the directive's input expects an array, so you would write [appForbiddenName]="['admin']" there.
Common errors
- Message never appears. The key string in the template does not match the key the validator returns.
hasError('forbidden')will not findforbiddenName. Copy the key from the validator. - Message appears on load. The condition checks only
invalid. Add thedirty || touchedcheck. - Message does not appear after clicking submit. The fields are untouched. Call
markAllAsTouched(). - Message flashes while typing.
touchedonly changes on blur, butdirtychanges on the first keystroke. If you want errors only after leaving the field, usetouchedalone. - Compile error on
errors.required. Strict templates reject property access on an index-signature type that may benull. Useerrors?.['required'], or usehasError. - Control set with
setValueshows no error. Programmatic changes do not mark a control dirty or touched. CallmarkAsTouched()ormarkAsDirty()yourself if you want errors to show.
Exercise
A signup form has a group validator that returns { passwordsMismatch: true }. You write @if (form.controls.confirm.hasError('passwordsMismatch')) and the message never shows, even when the passwords differ. Why, and how do you fix it?
Show answer
The group validator stores its error on the FormGroup, not on the confirm control, so the confirm control's errors is null. Read it from the group instead: @if (form.hasError('passwordsMismatch') && form.controls.confirm.touched). You can also call form.hasError('passwordsMismatch') on the group variable you already have.
Exercise
A username control has Validators.required and an async uniqueUsernameValidator. The user has not typed anything and submits the form. Will the "Checking availability…" message appear? Explain, and say what form.valid and form.invalid return for a control that is mid-check.
Show answer
No. Async validators run only after all synchronous validators pass, and required fails on an empty value, so the control is INVALID with a required error and never enters PENDING. For a control that is mid-check, valid and invalid are both false, because its status is PENDING. Use !form.valid rather than form.invalid to disable a submit button until checks finish.