Template-driven forms are simpler and rely heavily on Angular directives in the template rather than creating a form model in the TypeScript component. They are suitable for simple forms.
1️⃣ Import FormsModule
First, you need to import FormsModule
in your module (app.module.ts
):
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
FormsModule // <-- important
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
2️⃣ Create the Template
In template-driven forms, you define the form directly in your template using the ngForm
directive.
<!-- app.component.html -->
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
<div>
<label for="name">Name:</label>
<input
type="text"
id="name"
name="name"
ngModel
required
#name="ngModel"
/>
<div *ngIf="name.invalid && name.touched" style="color:red">
Name is required.
</div>
</div>
<div>
<label for="email">Email:</label>
<input
type="email"
id="email"
name="email"
ngModel
required
email
#email="ngModel"
/>
<div *ngIf="email.invalid && email.touched" style="color:red">
Enter a valid email.
</div>
</div>
<button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
✅ Key points:
ngModel
binds the form input to a model.#name="ngModel"
creates a template reference variable to track validation state.ngForm
tracks the overall form state.- Angular provides built-in validators like
required
andemail
.
3️⃣ Handle Submission in Component
In your component (app.component.ts
):
import { Component } from '@angular/core';
import { NgForm } from '@angular/forms';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
onSubmit(form: NgForm) {
console.log('Form Value:', form.value);
console.log('Form Valid:', form.valid);
}
}
4️⃣ Advantages of Template-Driven Forms
- Simple and easy to set up for small forms.
- Less boilerplate than reactive forms.
- Works well with simple validation.
5️⃣ Limitations
- Not ideal for complex forms.
- Harder to unit-test.
- Logic is spread between template and component.