Sub topic 5
Showing errors in the template
This chapter assumes you can build a reactive form with FormControl and FormGroup. It also assumes you have written a validator function that returns ValidationErrors | null. Here you will connect those errors to the template, so users see a message when, and only when, it helps them.
Where the errors live
Angular runs your validators and stores the result on the control. Three members matter for display:
| Member | What it gives you |
|---|---|
| `control.errors` | The merged `ValidationErrors` object, or `null` when the control is valid |
| `control.hasError('key')` | `true` if that error key is present |
| `control.getError('key')` | The value stored under that key, or `null` |
Recall that Angular merges the errors of every failing validator. If Validators.required and noWhitespaceValidator both fail, errors contains both keys. The template can therefore test each key on its own and show a separate message for each.
The error key is the contract between the validator and the template. If the validator returns { whitespace: true }, the template must ask for 'whitespace'. A mismatched key does not raise an error. The message simply never appears.
Control state flags
Showing a message based on invalid alone has a flaw. An empty required field is invalid from the moment the form renders, so the user would see "Name is required." before typing anything. Use the interaction flags to decide when to show it.
touchedbecomestrueafter the control loses focus.untouchedis the opposite.dirtybecomestrueafter the user changes the value in the UI.pristineis the opposite.invalidistruewhenerrorsis notnull. It is alsofalsewhile an async validator is still running.
A common rule is to show errors when the control is invalid and either dirty or touched.
A complete example
The component exposes the control through a getter so the template stays short.
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { noWhitespaceValidator } from './no-whitespace.validator';
import { forbiddenNameValidator } from './forbidden-name.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() {
return this.form.controls.name;
}
onSubmit(): void {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
console.log(this.form.getRawValue());
}
}The template, in name-form.component.html, uses the built-in @if control flow, which needs Angular 17 or later:
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<label for="name">Name</label>
<input id="name" type="text" [formControl]="name" />
@if (name.invalid && (name.dirty || name.touched)) {
@if (name.hasError('required')) {
<p>Name is required.</p>
}
@if (name.hasError('whitespace')) {
<p>Name cannot be only whitespace.</p>
}
@if (name.hasError('forbiddenName')) {
<p>"{{ name.getError('forbiddenName').value }}" is not allowed.</p>
}
}
<button type="submit">Save</button>
</form>Three things to notice:
- The outer
@ifis the timing rule. The inner@ifblocks pick the message. - The
forbiddenNamemessage reads the detail the factory stored in the error object:{ forbiddenName: { value } }. This is why validators should return useful values and not justtrue. onSubmitcallsmarkAllAsTouched()when the form is invalid. Without it, a user who clicks Save on an untouched form sees nothing, because no control is dirty or touched yet.
Group-level errors
A cross-field validator reports its error on the group, not on a child control. The check therefore goes on the group:
@if (form.hasError('passwordsMismatch') && form.controls.confirm.touched) {
<p>Passwords do not match.</p>
}Using the confirm control's touched flag keeps the message hidden until the user has visited that field. The group itself has no focus, so its own touched flag is a poor trigger.
Common mistakes
- Wrong key.
hasError('whitespaces')never matches{ whitespace: true }. Copy the key from the validator. - Reading
errors.keydirectly.name.errors.whitespacefails strict template type checks whenerrorsmay benull. UsehasErrorandgetError. - Showing errors during async checks. While an async validator runs, the status is
PENDING, andinvalidisfalse. A message tied toinvalidwill not flash. If you want a "Checking..." hint, testname.pending.
Exercise
A password confirmation form uses a group-level validator that returns { passwordsMismatch: true }. The template contains @if (form.controls.confirm.hasError('passwordsMismatch')), and the message never appears even when the passwords differ. What is wrong, and how do you fix it?
Show answer
The validator is attached to the group, so the error is stored on the group's errors, not on the confirm control. Check form.hasError('passwordsMismatch') instead. Optionally combine it with form.controls.confirm.touched so the message waits until the user has visited the field.