Template-Driven Forms with ngModel
Two Form Styles
| Template-driven | Reactive | |
|---|---|---|
| Defined in | The template (HTML) | The component class (TypeScript) |
| Best for | Small, simple forms | Complex forms, dynamic fields, testing |
| Module | FormsModule | ReactiveFormsModule |
A Contact Form
typescript
import { Component } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
@Component({
selector: 'app-contact',
imports: [FormsModule],
templateUrl: './contact.html',
})
export class Contact {
model = { name: '', email: '', message: '' };
sent = false;
submit(form: NgForm) {
if (form.invalid) return;
console.log('Sending', this.model);
this.sent = true;
form.resetForm();
}
}
html
<form #f="ngForm" (ngSubmit)="submit(f)" novalidate>
<label for="name">Name</label>
<input id="name" name="name" [(ngModel)]="model.name" #name="ngModel" required minlength="2">
@if (name.invalid && (name.dirty || name.touched || f.submitted)) {
<div class="error">
@if (name.errors?.['required']) { Name is required. }
@if (name.errors?.['minlength']) { At least 2 characters. }
</div>
}
<label for="email">Email</label>
<input id="email" name="email" type="email" [(ngModel)]="model.email" #email="ngModel" required email>
@if (email.invalid && (email.dirty || email.touched || f.submitted)) {
<div class="error">Enter a valid email address.</div>
}
<label for="msg">Message</label>
<textarea id="msg" name="message" [(ngModel)]="model.message" required></textarea>
<button type="submit" [disabled]="f.invalid">Send</button>
</form>
@if (sent) { <p class="success">Thank you! Message sent.</p> }
Every ngModel needs a name: Inside a
<form>, each control must have a name attribute, or Angular throws an error.
Control State
| Property | True when |
|---|---|
valid / invalid | Passes / fails all validators |
touched / untouched | User has left the field / not yet |
dirty / pristine | Value changed / not changed |
errors | Object with the failed validators |
CSS Classes Added Automatically
css
input.ng-invalid.ng-touched { border: 2px solid crimson; }
input.ng-valid.ng-touched { border: 2px solid seagreen; }
Built-In Validator Attributes
requiredminlength="3"andmaxlength="20"min="1"andmax="100"for numberspattern="[A-Za-z]+"email
When to switch: If your form has many fields, groups that repeat, cross-field rules or complex tests, move to reactive forms.
Conclusion
Template-driven forms need FormsModule, ngModel with a name, template reference variables and attribute validators. They are quick for small forms.
Quick Summary: FormsModule + [(ngModel)] + name + #ref="ngModel" + required/email.

