Template-driven forms in Angular allow you to create forms using HTML template syntax and Angular directives like ngModel and ngForm. These forms are simple to use, easy to set up, and best suited for smaller or less complex form scenarios.
FormsModule: Must be imported in app.module.ts to use template-driven features like ngModel.[(ngModel)]: Two-way data binding between form inputs and component properties.ngForm directive: Applied automatically to forms and can be accessed using a template reference variable like #userForm="ngForm".required, minlength, etc., combined with Angular state.FormsModule in your root or feature module to enable template-driven forms.[(ngModel)] on input elements to bind them to properties in your component class.#userForm="ngForm" to the <form> tag to access form state (valid, invalid, touched, etc.).(ngSubmit) on the form to handle submission in the component class.
// app.module.ts - register FormsModule to enable template-driven forms
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],
bootstrap: [AppComponent]
})
export class AppModule {}
// app.component.ts - component backing the template-driven form
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
user = { name: '', email: '' };
submitForm() {
console.log('Form Submitted', this.user);
}
}
<!-- app.component.html - template-driven form with two-way binding and validation -->
<form #userForm="ngForm" (ngSubmit)="submitForm()">
<label>Name:</label>
<input
type="text"
name="name"
[(ngModel)]="user.name"
required
>
<br><br>
<label>Email:</label>
<input
type="email"
name="email"
[(ngModel)]="user.email"
required
>
<br><br>
<button type="submit" [disabled]="!userForm.form.valid">
Submit
</button>
</form>
In the template-driven form above:
[(ngModel)]="user.name" and [(ngModel)]="user.email" create two-way data binding between the input fields and the user object in the component.#userForm="ngForm" creates a local reference to the form’s Angular NgForm instance, letting you access properties like userForm.form.valid.[disabled]="!userForm.form.valid", ensuring users cannot submit incomplete data.submitForm() runs and logs the user object to the console.After entering a valid name and email and clicking Submit, the browser console might show:
// Output shown in the browser console when form is submitted
Form Submitted { name: 'Alex', email: 'alex@example.com' }
FormsModule in the module where you want to use [(ngModel)].ngModel also has a name attribute so Angular can track its state.required, minlength, and type="email" to enforce validation rules.