Sub topic 1
How template-driven forms work and when to use them
Prerequisites
Assume you know Angular components, TypeScript classes, property and event binding, template reference variables, and basic HTML form controls.
How template-driven forms work and when to use them
A template-driven form is an Angular form whose structure and validation rules are declared mainly in the template. Angular reads directives such as ngModel and ngForm, then creates the form model and tracks each control.
A reactive form creates that model explicitly in TypeScript. Template-driven forms usually need less code and work well for small or moderately complex forms. Reactive forms are a better choice when the form is large, generated dynamically, or needs detailed programmatic control and testing.
Enabling FormsModule in a component
FormsModule provides the directives for template-driven forms. In a standalone component, import it in the component metadata:
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-profile',
standalone: true,
imports: [FormsModule],
templateUrl: './profile.component.html',
})
export class ProfileComponent {
model = { name: '' };
}In a module-based application, add FormsModule to the module's imports array instead.
Binding inputs with ngModel
Use [(ngModel)] for two-way binding. Angular writes the component value into the input and writes user changes back to the component. A named control must have a name attribute so Angular can register it with the form.
<form #f="ngForm">
<label for="name">Name</label>
<input
id="name"
name="name"
[(ngModel)]="model.name"
required
minlength="3"
/>
<button type="submit">Save</button>
</form>The required and minlength attributes become Angular validation rules because FormsModule is enabled.
The form as a whole: NgForm and #f="ngForm"
NgForm is the directive Angular attaches to a normal <form> element. The template reference variable #f="ngForm" gives access to that directive. For example, f.valid reports whether every registered control is valid, and f.value contains the form values.
Exercise
Why does this form use both [(ngModel)]="model.name" and #f="ngForm"?
Show answer
ngModel synchronizes one control with component data, while NgForm tracks the complete form and its validity.