Sub topic 7
Showing validation messages at the right time
This chapter assumes you know Angular components and templates, template reference variables, and how ngModel binds an input to component data. It also assumes you have seen required and minlength on an input. Here you decide when an error message appears, and how to make it readable to assistive technology.
Why timing matters
Angular validates a control as soon as it is created. An empty required field is invalid on first render, before the user has typed anything. If you show errors whenever invalid is true, the form opens covered in red messages.
Angular tracks interaction state to solve this. Two flags matter most:
touchedbecomes true after the control loses focus.dirtybecomes true after the user changes the value.
The usual rule is to show an error when the control is invalid and either touched or dirty.
Reading state through a reference variable
Export the NgModel directive into a template reference variable with #name="ngModel". The variable gives you the control's invalid, dirty, touched, and errors properties.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-signup',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<label for="name">Name</label>
<input
id="name"
name="name"
[(ngModel)]="model.name"
#name="ngModel"
required
minlength="3"
[attr.aria-invalid]="name.invalid && (name.dirty || name.touched)"
aria-describedby="name-errors"
/>
<div id="name-errors" role="alert">
@if (name.invalid && (name.dirty || name.touched)) {
@if (name.errors?.['required']) {
<p>Name is required.</p>
}
@if (name.errors?.['minlength']) {
<p>Name must be at least 3 characters.</p>
}
}
</div>
<button type="submit" [disabled]="f.invalid">Save</button>
</form>
`,
})
export class SignupComponent {
model = { name: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}The errors object has one key per failing validator. Checking errors?.['required'] and errors?.['minlength'] lets you show a message specific to each failure. The ?. is needed because errors is null when the control is valid.
Making messages accessible
Three details help screen reader users:
role="alert"makes the container announce new content when it changes. The container stays in the DOM and only its contents change, so the announcement fires reliably.aria-describedbylinks the input to the message container, so the message is read when the input gets focus.aria-invalidtells assistive technology the value is not acceptable. Binding it with[attr.aria-invalid]writes"true"or"false"as a string attribute.
Common errors
- Using
name.errors.minlengthwithout?.or bracket access.errorscan benull, and strict templates report that. Usename.errors?.['minlength']. - Forgetting the
nameattribute. Inside a<form>,ngModelrequiresname(or[ngModelOptions]="{standalone: true}"). Without it Angular throws an error at runtime. - Showing errors on
invalidalone. The form looks broken on first load. Add thedirty || touchedcondition. - Disabling the submit button as the only feedback. A disabled button with no visible reason leaves users guessing. Show messages for untouched fields after a failed submit attempt, as the next chapter covers with
ngSubmitandsubmittedstate.
Summary of the rule
| Control state | Show errors? |
|---|---|
| valid | No |
| invalid, pristine, untouched | No |
| invalid, dirty | Yes |
| invalid, touched | Yes |
Exercise
A user tabs through an empty required field without typing, then moves on. Which flag makes the "Name is required." message appear, and why does it not appear before that?
Show answer
The touched flag. The control is invalid from the start, but dirty is false because the value never changed, and touched is false until the control loses focus. After the user tabs away, touched becomes true, so invalid && (dirty || touched) is true and the message appears.
Exercise
Why does the template use name.errors?.['minlength'] instead of name.errors.minlength?
Show answer
errors is null when the control has no errors, so direct property access fails type checking in strict templates. The optional chaining with bracket access is safe for null. The bracket form also satisfies TypeScript's index-signature rules for ValidationErrors.