Difference Between Template-driven and Reactive Forms in Angular
What are Forms in Angular?
In Angular there are two approaches to creating forms:
- Template-driven forms — forms built based on templates (HTML).
- Reactive forms — forms managed from TypeScript code.
Comparison Table
| Characteristic | Template-driven Forms | Reactive Forms |
|---|---|---|
| Foundation | HTML template | TypeScript code |
| Module | FormsModule | ReactiveFormsModule |
| Management | Declarative (via template) | Imperative (via code) |
| Approach | Light, declarative | Flexible, programmatic |
| Validation | Via HTML attributes + directives | Via API and methods |
| Testing | More complex | Easier |
| Suitable for | Simple forms | Complex/dynamic forms |
Template-driven Form Example
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm)">
<input name="username" ngModel required />
<input name="email" ngModel email />
<button type="submit">Submit</button>
</form>
onSubmit(form: NgForm) {
console.log(form.value);
}
- Uses
ngModelfor data binding. - Directives (
required,email) for validation. - Logic is in template.
Reactive Form Example
import { FormGroup, FormControl, Validators } from '@angular/forms';
form = new FormGroup({
username: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email])
});
onSubmit() {
console.log(this.form.value);
}
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<input formControlName="username" />
<input formControlName="email" />
<button type="submit">Submit</button>
</form>
- Management completely in TS code.
- Validation set in FormControl via Validators.
- Better suited for complex scenarios.
When to Use?
| Scenario | Recommended approach |
|---|---|
| Simple login form | Template-driven |
| Complex dynamic form with logic and validation | Reactive |
| Need for scaling and testing | Reactive |
| Quick and simple form implementation | Template-driven |
Important:
Both approaches can be combined, but better choose one and stick with it throughout project for consistency.