Sub topic 8
Reading Status, Touched, and Dirty State to Show Errors
Validators decide whether a value is acceptable. They don't decide when the user should be told. If you show every error as soon as the page loads, the user sees a red form before typing anything. If you hide errors until submit, the user gets no feedback while filling the form in. Reactive forms track several kinds of state on every control so you can choose the moment yourself.
This chapter assumes you can already build a FormGroup, bind it with formGroup and formControlName, and attach built-in validators such as Validators.required and Validators.email.
The Three Kinds of State
Every FormControl, FormGroup, and FormArray extends AbstractControl, so all three expose the same state properties.
| Property | Values | What changes it | Column |
|---|---|---|---|
| `status` | `'VALID'`, `'INVALID'`, `'PENDING'`, `'DISABLED'` | Running validators, async validators, `disable()`/`enable()` | |
| `valid` / `invalid` / `pending` / `disabled` | booleans | Derived from `status` | |
| `touched` / `untouched` | booleans | The user blurs (leaves) the field, or you call `markAsTouched()` | |
| `dirty` / `pristine` | booleans | The user changes the value in the UI, or you call `markAsDirty()` | |
| `errors` | `ValidationErrors \ | null` | Each validation run |
Status describes the value. Touched and dirty describe what the user has done with the field. A control can be invalid and pristine at once, which is the normal state of an empty required field on a fresh form.
Reading Errors
When a control is valid, errors is null. When it is invalid, errors is an object with one key per failing validator. The value under each key often carries detail:
import { FormControl, Validators } from '@angular/forms';
const name = new FormControl('ab', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
});
console.log(name.errors);
// { minlength: { requiredLength: 3, actualLength: 2 } }
console.log(name.hasError('minlength')); // true
console.log(name.getError('minlength')?.requiredLength); // 3
console.log(name.hasError('required')); // falsehasError(code, path?) and getError(code, path?) also take an optional path, so a parent can check a child: form.hasError('required', 'email'). Use the path form in templates when you'd rather not write a getter for every control.
A Complete Error-Display Pattern
The usual rule is to show an error when the control is invalid and the user has either left the field or tried to submit. The component below follows that rule.
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
@Component({
selector: 'app-signup-form',
standalone: true,
imports: [ReactiveFormsModule],
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>
<label>
Username
<input formControlName="username" />
</label>
@if (showErrors(form.controls.username)) {
@if (form.controls.username.hasError('required')) {
<p class="error">Username is required.</p>
}
@if (form.controls.username.getError('minlength'); as err) {
<p class="error">
Use at least {{ err.requiredLength }} characters
(you have {{ err.actualLength }}).
</p>
}
}
<label>
Email
<input type="email" formControlName="email" />
</label>
@if (showErrors(form.controls.email) && form.controls.email.hasError('email')) {
<p class="error">Enter a valid email address.</p>
}
<button type="submit">Create account</button>
<p>Status: {{ form.status }} | Dirty: {{ form.dirty }} | Touched: {{ form.touched }}</p>
</form>
`,
styles: [`
input.ng-invalid.ng-touched { border-color: #c62828; }
.error { color: #c62828; margin: 0.25rem 0; }
`],
})
export class SignupFormComponent {
form = new FormGroup({
username: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.minLength(3)],
}),
email: new FormControl('', {
nonNullable: true,
validators: [Validators.required, Validators.email],
}),
});
showErrors(control: FormControl<string>): boolean {
return control.invalid && control.touched;
}
onSubmit(): void {
if (this.form.invalid) {
this.form.markAllAsTouched();
return;
}
console.log('submitting', this.form.getRawValue());
this.form.reset();
}
}The novalidate attribute turns off the browser's own validation bubbles so that Angular's messages are the only ones shown. markAllAsTouched() walks the whole control tree, so every invalid field shows its message after a failed submit. reset() sets the controls back to pristine and untouched, and the messages disappear.
Parent State Aggregates Child State
A group's state is computed from its children:
- The group is
INVALIDif any enabled child is invalid or the group's own validator fails. - The group is
PENDINGif no child is invalid but at least one is still running an async validator. - The group is
touchedif any child is touched, anddirtyif any child is dirty. - The group is
DISABLEDonly when every child is disabled.
So form.dirty answers "has the user changed anything?", which is useful for an "unsaved changes" prompt. form.touched only says that at least one field was visited.
CSS Classes Angular Adds for You
The formControlName and formGroup directives apply status classes to the host element: ng-valid, ng-invalid, ng-pending, ng-pristine, ng-dirty, ng-touched, and ng-untouched. The <form> element also gets ng-submitted after a submit. You can often style invalid fields with CSS alone, as the input.ng-invalid.ng-touched rule above does, and keep conditional logic out of the template.
Gotchas
`invalid` is not the same as `!valid`
valid and invalid are both false when the status is PENDING or DISABLED. If you write [disabled]="!form.valid", the button stays disabled while an async check runs. With [disabled]="form.invalid", it is enabled during that time. Choose deliberately, and check pending when it matters.
Programmatic changes don't make a control dirty
setValue() and patchValue() change the value and re-run validation, but they leave dirty and touched alone. Only UI input from the value accessor marks a control dirty. If you load saved data with patchValue(), the form stays pristine, which is usually what you want for an "unsaved changes" check. If you need the other behavior, call markAsDirty() yourself.
Touched is set on blur, not on focus
Clicking into a field and typing doesn't set touched. The user has to leave the field first. If you want errors to appear while the user types, check dirty instead: control.invalid && (control.dirty || control.touched).
Disabled controls have no errors
Disabling a control sets its status to DISABLED, sets errors to null, and excludes the control from the parent's validity. A required field you disable can never block submission.
Templates read state on every change detection
showErrors() is a cheap method, so calling it from the template is fine. Avoid heavy computation in such helpers, because Angular calls them on every change detection cycle.
Exercise
A profile form loads saved data with patchValue() on init. The save button uses [disabled]="!form.dirty || form.invalid". A user opens the form and immediately clicks into and out of the email field without typing. Is the button enabled, and why?
Show answer
It stays disabled. patchValue() does not mark controls dirty, and focusing and blurring the email field only sets touched. form.dirty is still false, so !form.dirty is true and the button is disabled.
Exercise
An async username validator is running, and every other control is valid. What do form.status, form.valid, and form.invalid report?
Show answer
form.status is 'PENDING', and both form.valid and form.invalid are false. A pending group is neither valid nor invalid until the async validator finishes.
Exercise
Write the condition for showing a control's error messages as soon as the user starts typing, and also after the user leaves the field or a failed submit calls markAllAsTouched().
Show answer
control.invalid && (control.dirty || control.touched). Typing sets dirty, and blurring or markAllAsTouched() sets touched.