Template-Driven Forms
Building a simple form with ngModel and letting Angular's template-driven forms track its state for you.
2 phút đọc
You've already seen [(ngModel)] used to sync a single input with a property. Angular's template-driven forms build on exactly that, adding form-level tracking — validity, submission, which fields have been touched — with very little extra code.
A basic form
import { Component } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
@Component({
selector: 'app-signup-form',
imports: [FormsModule],
template: `
<form #signupForm="ngForm" (ngSubmit)="onSubmit(signupForm)">
<input name="email" [(ngModel)]="model.email" required email />
<input name="password" type="password" [(ngModel)]="model.password" required minlength="8" />
<button type="submit" [disabled]="signupForm.invalid">Sign up</button>
</form>
`,
})
export class SignupFormComponent {
model = { email: '', password: '' };
onSubmit(form: NgForm): void {
console.log('Submitting', form.value);
}
}#signupForm="ngForm" is a template reference variable — it gives the template a handle on the directive Angular attaches to every <form> automatically, exposing properties like .invalid, .value, and .submitted. Every [(ngModel)] inside the form registers itself with that form directive, which is how signupForm.invalid knows to reflect both inputs' validity without you wiring that up by hand.
required, email, and minlength="8" here are plain HTML validation attributes — Angular recognizes them and turns each one into a validation rule automatically, no separate configuration needed.
Why the name "template-driven"
The form's structure and validation rules are declared entirely in the template — the component class barely does more than hold the data and react to submission. That's the appeal for a simple form: less code, and the validation rules sit right next to the inputs they apply to, easy to read at a glance.
Where it starts to strain
As a form grows — fields that depend on each other, validation rules that need custom logic, dynamically added fields — keeping everything in the template gets harder to follow and harder to test, since there's no form object in the component class to unit test independently of rendering the template. That's the exact gap Angular's other form system, reactive forms, is built to fill, covered in the next lesson.
When template-driven forms are still the right choice
For a short form — a login screen, a single search box, a simple settings toggle — template-driven forms usually get you there faster with less boilerplate. The choice isn't about one approach being universally better; it's about matching the form's complexity to how much structure you actually need.