Sub topic 1
How template-driven forms work and when to use them
Prerequisites
This chapter assumes you know:
- Basic TypeScript classes and types.
- Angular components and templates, including property binding, event binding, and template reference variables.
- Basic HTML form elements and validation attributes such as
required.
The working model
Angular has two ways to build forms. In template-driven forms, you write most of the form in the component template. Directives such as ngModel and ngForm create the form model for you behind the scenes. In reactive forms, you build the model yourself in the component class with FormGroup and FormControl, and the template only binds to it.
In both approaches Angular tracks a tree of controls. Each control holds a value and its state: valid or invalid, touched or untouched, dirty or pristine. The difference is who creates the tree. In a template-driven form, the directives create it when the template renders.
Three directives do most of the work:
NgFormattaches to every<form>element onceFormsModuleis imported. It tracks the controls inside it.NgModelattaches to an input that has[(ngModel)]and anameattribute. It registers that input as a control in the parent form.NgModelGroupgroups several controls under one key. A later chapter covers it.
A first example
This standalone component imports FormsModule, binds an input to model.name, and shows an error only after the user has interacted with the field.
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-signup',
imports: [FormsModule],
template: `
<form #f="ngForm" (ngSubmit)="onSubmit()">
<label for="name">Name</label>
<input
id="name"
name="name"
[(ngModel)]="model.name"
#name="ngModel"
required
minlength="3"
/>
@if (name.invalid && (name.dirty || name.touched)) {
<div role="alert">
@if (name.errors?.['required']) {
<p>Name is required.</p>
}
@if (name.errors?.['minlength']) {
<p>Name must be at least 3 characters.</p>
}
</div>
}
<button type="submit" [disabled]="f.invalid">Save</button>
</form>
`,
})
export class SignupComponent {
model = { name: '' };
onSubmit() {
console.log('Submitted', this.model);
}
}Note what the example does:
imports: [FormsModule]turns onNgFormandNgModel.[(ngModel)]="model.name"keeps the input andmodel.namein sync.#f="ngForm"and#name="ngModel"expose the form and control objects to the template.requiredandminlengthare plain HTML attributes. Angular recognizes them and adds validators.- The error block waits for
dirtyortouched, so the user doesn't see an error before typing.
Template-driven or reactive?
| Concern | Template-driven | Reactive |
|---|---|---|
| Where the model lives | Template, created by directives | Component class, created explicitly |
| Setup effort | Low for simple forms | More code up front |
| Validation | Attributes and directives | Functions on controls |
| Dynamic fields | Awkward | Natural |
| Unit testing | Needs rendering and change detection | Can test the model without a template |
Choose template-driven forms for small, mostly static forms such as login, signup, or a settings panel. Choose reactive forms when you need dynamic fields, complex cross-field rules, or model-level tests. Pick one approach per form. Mixing them in the same form causes confusing errors.
Common errors
- No
FormsModuleimport.ngModelis then an unknown property, and the compiler reports an error. - Missing
nameattribute. AnngModelinput inside a<form>withoutnamethrows a runtime error, because the form needs a key for the control. - Reading state too early. Controls register after the first render. Template reference variables work in the template, but code in the constructor can't see them.
Exercise
A teammate adds <input [(ngModel)]="email" /> inside a <form> and gets a runtime error, although FormsModule is imported. What is the likely cause, and how do you fix it?
Show answer
The input has no name attribute. Inside a form, ngModel registers the control under its name, so the name is required. Add name="email" to the input, or add [ngModelOptions]="{ standalone: true }" if the input shouldn't belong to the form.