Template-Driven Form
Template-driven forms are built around HTML-driven components. They rely heavily on directives in the template to handle form validation and data submission. As the name suggests, in Template-Driven Form, the form logic is mainly in the template file. It uses Angular’s “ngModel” two-way data-binding directive to create and manage the underlying form instance.
Syntax:
<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
<input name="name" ngModel required>
<button type="submit">Submit</button>
</form>
Features of Template-Driven Forms
- Easy to get started with, suitable for simple forms.
- Minimal TypeScript code required.
- Automatically tracks form and input state.
- Two-way data binding with
ngModel
. - Built-in validation with HTML attributes.
Example:
Create a new project with the help of Angalur cli.
ng new forms
<!-- app.component.html -->
<h3>Complex Template Driven Form</h3>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)">
<div>
<label for="name">Name: </label>
<input
type="text"
id="name"
name="name"
[(ngModel)]="credentials.name"
required
/>
</div>
<div>
<label for="email">Email: </label>
<input
type="email"
id="email"
name="email"
[(ngModel)]="credentials.email"
required
email
/>
</div>
<div>
<label for="password">Password: </label>
<input
type="password"
id="password"
name="password"
[(ngModel)]="credentials.password"
required
/>
</div>
<button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>
//app.component.ts
import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-tdf-complex',
standalone: true,
imports: [FormsModule],
templateUrl: './tdf-complex.component.html',
styleUrl: './tdf-complex.component.css',
})
export class TdfComplexComponent {
credentials: any = {};
onSubmit(formValue: any) {
console.log('Form value: ', formValue);
}
}
Output:
Template Driven Form vs Reactive Form in Angular.
Angular provides two main approaches for creating forms: Template-Driven Forms and Reactive Forms. In this article, we’ll see both methods, highlighting their features, and providing code examples. We’ll also compare them side by side to help you understand when to use each.