Sub topic 2
Tracking Control State in Template-Driven Forms
Assume you know Angular components, templates, template reference variables, and basic HTML forms. Angular's FormsModule creates a control for each named [(ngModel)] input. Each control tracks both its value and its state.
Tracking `touched`, `dirty`, and `valid`
touchedistrueafter the user focuses and leaves the control.dirtyistrueafter the user changes the value.validistruewhen every validator passes.invalidis the opposite ofvalid.
These states let you delay errors until the user has interacted with a field.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-profile',
standalone: true,
imports: [FormsModule],
template: `
<form #form="ngForm" (ngSubmit)="save()" novalidate>
<label for="name">Name</label>
<input
id="name"
name="name"
[(ngModel)]="model.name"
#name="ngModel"
required
minlength="3"
pattern="[A-Za-z ]+"
/>
@if (name.invalid && (name.touched || name.dirty)) {
<div role="alert">
@if (name.errors?.['required']) {
<p>Name is required.</p>
}
@if (name.errors?.['minlength']) {
<p>Name needs at least three characters.</p>
}
@if (name.errors?.['pattern']) {
<p>Name may contain letters and spaces only.</p>
}
</div>
}
<label for="email">Email</label>
<input
id="email"
name="email"
type="email"
[(ngModel)]="model.email"
#email="ngModel"
required
email
/>
@if (email.invalid && (email.touched || email.dirty)) {
<p role="alert">Enter a valid email address.</p>
}
<button type="submit" [disabled]="form.invalid">Save</button>
<button type="button" (click)="form.resetForm()">Reset</button>
</form>
`,
})
export class ProfileComponent {
model = { name: '', email: '' };
save() {
console.log(this.model);
}
}Showing messages at the right time
The condition control.invalid && (control.touched || control.dirty) prevents errors from appearing on an untouched form. The role="alert" attribute helps assistive technology announce the message. The required, minlength, pattern, and email attributes add built-in validators.
Submit and reset
ngSubmit runs only when the form submits. The form reference exposes its combined validity, so disabling the button prevents invalid submission. resetForm() clears values and returns controls to their initial, untouched, pristine state.
Exercise
Why can a control be invalid but show no error message?
Show answer
It may still be untouched and pristine. The template deliberately waits for touched or dirty before showing feedback.