Sub topic 5
Tracking control state: touched, dirty, valid
This chapter assumes you can write an Angular standalone component, import FormsModule, and bind an input with [(ngModel)]. You should also know how to create a template reference variable such as #name="ngModel". Here you will learn what state Angular tracks on each control, how that state is exposed in the template and in CSS, and which mistakes cause confusing behavior.
What control state is
Every ngModel directive creates a FormControl behind the scenes. That control keeps flags that describe what the user has done and whether the current value passes validation. You read the flags through a template reference variable exported by ngModel.
<input name="email" [(ngModel)]="model.email" #email="ngModel" required />
<p>valid: {{ email.valid }}, touched: {{ email.touched }}, dirty: {{ email.dirty }}</p>The variable email is the NgModel directive instance. It forwards the control's properties, so email.valid and email.touched work directly. Without ="ngModel", the variable would point to the DOM element, which has none of these flags.
The three pairs of flags
Angular groups state into three opposing pairs. Each flag is a boolean, and exactly one flag in each pair is true at any time.
| Flag pair | Meaning | When it changes |
|---|---|---|
| `pristine` / `dirty` | Has the user changed the value? | `dirty` becomes true on the first edit made through the UI. |
| `untouched` / `touched` | Has the user visited the control? | `touched` becomes true when the input fires a `blur` event. |
| `valid` / `invalid` | Do all validators pass? | Recomputed every time the value or a validator changes. |
There are two more statuses worth knowing. pending is true while an async validator is running. disabled is true when the control is disabled, and a disabled control is excluded from validation and from the form's value.
You can also read the single status string, which is one of VALID, INVALID, PENDING, or DISABLED.
How dirty differs from touched
These two are easy to confuse because they usually change close together. They respond to different events.
dirtyis set by user input. If a user types a character and deletes it, the control is still dirty, even though the value matches the original.touchedis set by blur. A user can tab through a field without typing and the control becomes touched but stays pristine.
Setting the value from code, for example by assigning model.name = 'Ada' in the component, does not make the control dirty. Only changes that come from the view do.
Reading state in the template
The most common use of these flags is deciding what to show. This component displays a hint only when the field is invalid and the user has interacted with it.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-state-demo',
imports: [FormsModule],
template: `
<form #f="ngForm">
<label for="nick">Nickname</label>
<input
id="nick"
name="nick"
[(ngModel)]="model.nick"
#nick="ngModel"
required
minlength="3"
/>
<ul>
<li>valid: {{ nick.valid }}</li>
<li>pristine: {{ nick.pristine }}</li>
<li>touched: {{ nick.touched }}</li>
<li>status: {{ nick.status }}</li>
</ul>
<p>Form valid: {{ f.valid }}, form dirty: {{ f.dirty }}</p>
</form>
`,
})
export class StateDemoComponent {
model = { nick: '' };
}Run this and watch the list. On load, valid is false because required fails on the empty string, pristine is true, and touched is false. Type one character and pristine flips to false, while valid stays false because of minlength. Click outside the field and touched becomes true.
Form-level state
The NgForm directive exposes the same flags for the whole form. The aggregation rules are what you need to remember.
- The form is
validonly if every enabled control is valid. - The form is
dirtyif any control is dirty. - The form is
touchedif any control has been touched.
So f.invalid is a convenient condition for disabling a submit button, and f.dirty works for a "you have unsaved changes" warning. Form-level flags change as soon as any single control changes, so they do not tell you which control caused the change. For that, read the control's own variable or inspect f.controls.
<button type="submit" [disabled]="f.invalid">Save</button>
<p>{{ f.dirty ? 'Unsaved changes' : 'No changes' }}</p>CSS classes Angular adds automatically
You do not always need to read flags in the template. Angular mirrors them as CSS classes on the input element. The ngModel directive adds these classes and keeps them in sync:
| Class | Applied when |
|---|---|
| `ng-pristine` / `ng-dirty` | The control is pristine or dirty. |
| `ng-untouched` / `ng-touched` | The control is untouched or touched. |
| `ng-valid` / `ng-invalid` | The control is valid or invalid. |
| `ng-pending` | An async validator is running. |
The <form> element receives the same classes through NgForm, so you can style the whole form. Combine the classes so the error style appears only after interaction.
input.ng-invalid.ng-touched {
border: 2px solid #b00020;
}
input.ng-valid.ng-touched {
border: 2px solid #1b7f3b;
}If you wrote input.ng-invalid alone, every required field would be red the moment the page loads, because empty required fields are invalid from the start. Pairing it with ng-touched or ng-dirty avoids that.
Choosing between touched and dirty
Use the flag that matches the behavior you want.
- Use
touchedwhen you want to wait until the user leaves the field. This avoids showing "too short" after the first typed character. It is the usual choice for error messages. - Use
dirtywhen you care whether the value changed, such as for an unsaved-changes prompt. - Use
touched || dirtyfor errors when you also want to catch a user who types and then keeps typing in the field, without waiting for blur. This is the condition used in the signup example earlier in this tutorial.
The form submit is a special case. A user may click Save without ever touching a field, so none of the fields would show errors. Handling that case is covered in the chapter on submitting and resetting.
Edge cases and common errors
The missing name attribute
Inside a <form>, every ngModel control must have a name attribute, or Angular throws an error like "If ngModel is used within a form tag, either the name attribute must be set or the form control must be defined as 'standalone'". If you really want a control that is not part of the form, set [ngModelOptions]="{ standalone: true }". A standalone control still tracks its own state, but it does not affect the parent form's validity or value.
Initial validity is not delayed
valid can be false at the very first render, and the first check may run after the view is initialized. Template expressions that read nick.valid right away can briefly show a different value than you expect. If Angular reports ExpressionChangedAfterItHasBeenCheckedError in development mode, it usually means you changed state inside a lifecycle hook that ran after the view was checked. Prefer reading state in the template and reacting in event handlers.
Valid does not mean touched
A control with a valid value can still be untouched. If you hide a success message behind valid alone, it appears before the user has done anything for a field with a default value. Check the interaction flag as well.
Programmatic changes bypass dirty
Because dirty only responds to user input, loading data from a service into model leaves the form pristine. This is usually what you want. If you need to mark a control yourself, call markAsDirty() or markAsTouched() on the control.
import { Component, viewChild } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
@Component({
selector: 'app-touch-all',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="save()">
<input name="city" [(ngModel)]="model.city" required />
<button type="submit">Save</button>
</form>
`,
})
export class TouchAllComponent {
model = { city: '' };
form = viewChild.required<NgForm>('f');
save() {
if (this.form().invalid) {
this.form().control.markAllAsTouched();
return;
}
console.log('Saved', this.model);
}
}Here markAllAsTouched() sets touched on every control, so the error messages that depend on touched appear for fields the user skipped.
Reset clears state
f.resetForm() resets values and returns every flag to pristine and untouched. Calling f.reset() clears values too but does not reset the submitted flag on NgForm, so resetForm() is the better choice after a successful save.
Summary of reading state
| You want to know | Read |
|---|---|
| Is this field acceptable right now? | `control.valid` |
| Has the user edited this field? | `control.dirty` |
| Has the user left this field? | `control.touched` |
| Is the whole form ready to submit? | `f.valid` |
| Is an async check running? | `control.pending` |
Exercise
A required text input has a default value of "Ada" set from the component class. The user tabs into the field and then out of it without typing. What are the values of pristine, touched, and valid afterward?
Show answer
pristine is true, because the value was never changed through the UI and programmatic assignment does not set dirty. touched is true, because the blur event occurred. valid is true, because "Ada" satisfies required.
Exercise
You style errors with input.ng-invalid { border: 2px solid red; } and users complain that every empty field is red when the page opens. How do you fix it, and why does the problem occur?
Show answer
Change the selector to input.ng-invalid.ng-touched (or .ng-dirty). Empty required fields are invalid from the first render, so ng-invalid alone matches them before the user has interacted. Adding the touched or dirty class limits the style to fields the user has visited or edited.