Template Driven Forms in Angular: What They Are and How They Work
ngModel. They rely on Angular's two-way data binding to manage form inputs and validation, making them simple and easy to use for basic forms.How It Works
Template driven forms work by letting you write most of the form setup directly in the HTML template. Imagine filling out a paper form where you check boxes and write answers; Angular watches those inputs and keeps track of what you type or select automatically.
Behind the scenes, Angular uses directives like ngModel to connect each form field to a variable in your component. This connection is two-way, meaning if you change the variable in code, the form updates, and if you type in the form, the variable changes too.
This approach is like having a helper who watches your form and keeps your data ready without you writing much code. It’s great for simple forms where you want quick setup and easy validation.
Example
This example shows a simple template driven form with a name input and a submit button. The form uses ngModel to bind the input to a variable and displays the entered name below.
import { Component } from '@angular/core'; @Component({ selector: 'app-simple-form', template: ` <form #formRef="ngForm" (ngSubmit)="submitForm()"> <label for="name">Name:</label> <input id="name" name="name" [(ngModel)]="userName" required /> <button type="submit" [disabled]="formRef.invalid">Submit</button> </form> <p *ngIf="submitted">Hello, {{ userName }}!</p> ` }) export class SimpleFormComponent { userName = ''; submitted = false; submitForm() { this.submitted = true; } }
When to Use
Use template driven forms when you have simple forms with a few fields and straightforward validation. They are perfect for quick setups like contact forms, login forms, or small surveys.
If your form needs complex validation, dynamic fields, or more control over form state, reactive forms might be a better choice. But for many everyday cases, template driven forms keep your code clean and easy to understand.
Key Points
- Template driven forms define form logic mainly in the HTML template.
- They use
ngModelfor two-way data binding. - Best suited for simple forms with basic validation.
- Angular automatically tracks form state and validity.
- Easy to set up without much TypeScript code.