LearnAI ToolsCareerPractice BuildsPlayContact
Lesson 3316 min read

Template-Driven Forms

Build forms primarily in the template using ngModel and Angular's automatic form/control state tracking.

What Are Template-Driven Forms?

Template-driven forms build most of a form's structure and validation directly in the template, using ngModel and directives — a natural fit for simple forms, and the more approachable of Angular's two official form approaches.

Building a Simple Form

import { Component } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';
@Component({
selector: 'app-signup',
standalone: true,
imports: [FormsModule],
template: `
<form #signupForm="ngForm" (ngSubmit)="onSubmit(signupForm)">
<input name="email" [(ngModel)]="email" required email />
<input name="password" [(ngModel)]="password" required minlength="8" />
<button type="submit" [disabled]="signupForm.invalid">Sign Up</button>
</form>
`,
})
export class SignupComponent {
email = '';
password = '';
onSubmit(form: NgForm) {
if (form.valid) {
console.log(this.email, this.password);
}
}
}

#signupForm="ngForm" exports the automatically created form model as a template reference variable, giving you access to its overall valid/invalid state and submission handling.

Built-in Validation Directives

DirectiveValidates
requiredThe field is not empty
emailThe value looks like a valid email address
minlength / maxlengthA string's length falls within a range
patternThe value matches a given regular expression

Showing Validation Errors

Each ngModel-bound field also exposes its own template reference variable with detailed validity state, letting you show field-specific error messages.

<input name="email" [(ngModel)]="email" required email #emailField="ngModel" />
<p *ngIf="emailField.invalid && emailField.touched">
Please enter a valid email.
</p>
.touched Avoids Premature Errors

Checking .touched (the user has interacted with and left the field) alongside .invalid prevents showing an error message the instant the page loads, before the user has had a chance to type anything.

FAQs

They work, but reactive forms (covered next) scale better for forms with many interdependent fields, dynamic fields, or complex custom validation logic.

Yes — any standalone component using [(ngModel)] or ngForm must import FormsModule directly.

Summary

Template-driven forms lean on ngModel and validation directives declared directly in markup — approachable for simple forms. Next, you'll learn reactive forms, Angular's more powerful, code-driven alternative.

Next Lesson →

Reactive Forms