Template-driven Forms
Angular offers two ways to build forms:
| Template-driven | Reactive | |
|---|---|---|
| Form model defined in | The template (ngModel directives) |
The component class (FormGroup, FormControl) |
| Import | FormsModule |
ReactiveFormsModule |
| Best for | Small, simple forms | Large, dynamic or heavily validated forms |
| Testing | Needs the template | Logic testable without the DOM |
This lesson covers template-driven forms: you add ngModel to inputs and Angular builds the form model behind the scenes.
A contact form
import { Component, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-contact',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="send(f.value)">
<label>Name <input name="name" [(ngModel)]="name" required /></label>
<label>Email <input name="email" type="email" [(ngModel)]="email" required email /></label>
<label>Topic
<select name="topic" [(ngModel)]="topic">
<option value="support">Support</option>
<option value="sales">Sales</option>
</select>
</label>
<label><input type="checkbox" name="copy" [(ngModel)]="copy" /> Send me a copy</label>
<button [disabled]="f.invalid">Send</button>
<p>Form valid: {{ f.valid }}</p>
</form>
`,
styles: `label { display: block; margin-bottom: 8px; } input, select { margin-left: 6px; }`,
})
export class Contact {
name = signal('Linh');
email = signal('');
topic = signal('support');
copy = signal(false);
send(value: unknown) {
console.log('submitted', JSON.stringify(value));
}
}submitted {"name":"Linh","email":"linh@example.com","topic":"support","copy":true}
Key points:
- Every
ngModelinside a<form>needs anameattribute — it becomes the key in the form's value. #f="ngForm"gives you a reference to the form directive, withvalue,valid,invalid,touched,reset()and more.(ngSubmit)fires on submit and prevents the browser's default page reload.requiredandemailare validator directives provided byFormsModule.
Control state
Each control tracks its state and adds CSS classes to the element accordingly:
| State | True when… | CSS class (true / false) |
|---|---|---|
touched |
The user focused and left the field | ng-touched / ng-untouched |
dirty |
The user changed the value | ng-dirty / ng-pristine |
valid |
All validators pass | ng-valid / ng-invalid |
A common rule is: show an error only after the user has touched the field. Export the control with #email="ngModel" to read its state:
import { Component, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-email-field',
imports: [FormsModule],
template: `
<input name="email" [(ngModel)]="email" #emailCtrl="ngModel" required email placeholder="you@example.com" />
@if (emailCtrl.invalid && emailCtrl.touched) {
@if (emailCtrl.hasError('required')) { <p class="err">Email is required.</p> }
@if (emailCtrl.hasError('email')) { <p class="err">That doesn't look like an email.</p> }
}
`,
styles: `
input.ng-invalid.ng-touched { border: 2px solid #dd0031; }
.err { color: #dd0031; margin: 4px 0; font-size: 14px; }
`,
})
export class EmailField {
email = signal('linh@');
}What the form value looks like
Behind the scenes NgForm collects each named control into an object and computes overall validity from the parts. A plain TypeScript model of that aggregation:
type Validator = (v: unknown) => string | null;
const required: Validator = (v) => (v === '' || v == null ? 'required' : null);
const email: Validator = (v) => (typeof v === 'string' && v !== '' && !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v) ? 'email' : null);
interface Control { value: unknown; validators: Validator[]; }
function evaluate(controls: Record<string, Control>) {
const value: Record<string, unknown> = {};
const errors: Record<string, string[]> = {};
for (const [key, c] of Object.entries(controls)) {
value[key] = c.value;
const errs = c.validators.map((fn) => fn(c.value)).filter((e): e is string => e !== null);
if (errs.length) errors[key] = errs;
}
return { value, valid: Object.keys(errors).length === 0, errors };
}
console.log(evaluate({
name: { value: 'Linh', validators: [required] },
email: { value: 'linh@', validators: [required, email] },
}));{
value: { name: 'Linh', email: 'linh@' },
valid: false,
errors: { email: [ 'email' ] }
}
Grouping fields
ngModelGroup nests part of the form value under a key, useful for addresses:
<div ngModelGroup="address">
<input name="street" [(ngModel)]="street" />
<input name="city" [(ngModel)]="city" />
</div>
<!-- f.value → { ..., address: { street: '...', city: '...' } } -->Tip: Template-driven forms are quick to write. When you need dynamic fields, cross-field validation or unit tests without a template, switch to reactive forms (next lesson).
Test yourself
What is required on every ngModel input inside a <form>?
- An id attribute
- A name attribute
- A placeholder
- A class
Which event should you bind to submit an Angular form?
(click)on the form(ngSubmit)(submitForm)(send)
Which CSS classes does a field have after the user changed it to an invalid value and left it?
- ng-pristine ng-valid ng-untouched
- ng-dirty ng-invalid ng-touched
- ng-dirty ng-valid ng-touched
- ng-pristine ng-invalid ng-touched