Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 74 ยท Forms

Template-Driven Forms

Build Angular forms in the template with FormsModule, ngModel and ngForm, use validation attributes and control states, and decide when this approach is the right one.

Almost every application collects input somewhere: sign-up, search, checkout, settings. Angular ships two form systems that do the same job in different styles. Template-driven forms describe the form in the HTML template: you add ngModel to inputs, add validation attributes like required, and Angular builds the form model behind the scenes. Reactive forms (the next lesson) build the model explicitly in TypeScript.

Template-driven forms are the quickest way to a working form, and you already know most of the syntax from two-way binding. This lesson shows how to wire a form, read validation state, show errors at the right moment, and decide whether this style fits your project.

The Angular code in this lesson is read-only, because the site can't run the Angular compiler. The runnable examples are hand-written stand-ins that re-implement the same ideas (validation rules from attributes, control states, when errors show) in plain TypeScript so you can try the logic. They are not Angular's real forms classes.

Setting up

Everything lives in FormsModule, which you import into the standalone component that has the form:

TypeScript
import { Component } from '@angular/core';
import { FormsModule, NgForm } from '@angular/forms';

@Component({
  selector: 'app-signup',
  imports: [FormsModule],
  templateUrl: './signup.component.html',
})
export class SignupComponent {
  model = { name: '', email: '', age: null as number | null, plan: 'free' };

  save(form: NgForm): void {
    if (form.invalid) {
      return;
    }
    console.log('sending', form.value);
    form.resetForm({ plan: 'free' });
  }
}
HTML
<form #f="ngForm" (ngSubmit)="save(f)">
  <label for="name">Name</label>
  <input id="name" name="name" [(ngModel)]="model.name" required minlength="2" #name="ngModel" />

  <label for="email">Email</label>
  <input id="email" name="email" type="email" [(ngModel)]="model.email" required email #email="ngModel" />

  <button type="submit">Create account</button>
</form>

Several things happen automatically:

  • NgForm attaches itself to every <form> once FormsModule is imported. #f="ngForm" gives the template a reference to it, so you can read f.valid, f.value or f.submitted.
  • ngModel registers each input as a control inside that form, using its name attribute as the key. A control inside a form without a name throws an error at runtime, so always set one (the key is also the property name in f.value).
  • #name="ngModel" exports the control so you can read its validity and errors (name.invalid, name.errors).
  • Angular adds the novalidate attribute for you, so the browser's own bubbles don't compete with your messages.
flowchart LR
  A["Template<br/>form, ngModel, required"] --> B["NgForm and NgModel<br/>directives"]
  B --> C["FormGroup with one<br/>FormControl per name"]
  C --> D["valid, touched, dirty<br/>plus ng-* CSS classes"]

The directives build the same control tree you'd write by hand in reactive forms; template-driven forms just hide it.

Validation by attribute

Validation rules are HTML attributes that Angular recognizes as directives:

Attribute Fails when
required the value is empty
minlength="3", maxlength="20" the text is shorter or longer than the limit
min="18", max="99" the number is below or above the limit
pattern="[A-Z]{3}" the value doesn't match the regular expression
email the value doesn't look like an email address

The validators ignore empty values, except required: an empty optional field with minlength is valid, which is the behavior you want. Whitespace counts as a value, so required alone doesn't catch a name made of spaces; add a pattern or a custom validator if that matters. Custom validators for template-driven forms are directives, which is one reason complex rules lean toward reactive forms.

Try the rules in a stand-in. validate returns an errors object like Angular's control.errors: null when valid, otherwise one key per failed rule.

TypeScript Stand-in: validation rules and errors objects

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Note that the optional code field is valid when empty, and that each failure carries details (requiredLength, actualLength) you can use in the message.

Control states

Each control tracks three pairs of flags, and the form (a group of controls) summarizes them:

  • valid / invalid: do all the rules pass?
  • touched / untouched: has the user focused and then left the field (a blur)?
  • dirty / pristine: has the user changed the value?

Angular also mirrors them as CSS classes on the element: ng-valid, ng-invalid, ng-touched, ng-untouched, ng-dirty and ng-pristine, so you can style a bad field without writing any TypeScript:

CSS
input.ng-invalid.ng-touched {
  border-color: #c0362c;
}

The form also has submitted, which turns true after the first submit event.

Showing errors at the right moment

An empty required field is technically invalid the moment the page loads, but shouting "Name is required" at someone who hasn't typed anything is unfriendly. The usual rule: show an error when the control is invalid and the user has either left the field (touched) or tried to submit (f.submitted).

HTML
<input id="email" name="email" type="email" [(ngModel)]="model.email"
       required email #email="ngModel"
       [attr.aria-invalid]="email.invalid && (email.touched || f.submitted)"
       aria-describedby="email-error" />

@if (email.invalid && (email.touched || f.submitted)) {
  <p id="email-error" role="alert">
    @if (email.errors?.['required']) { Enter your email address. }
    @else if (email.errors?.['email']) { That doesn't look like an email address. }
  </p>
}

role="alert" and aria-describedby make assistive technology announce the message and connect it to the field. The @if syntax is covered in control flow. Avoid disabling the submit button permanently while the form is invalid: users then can't discover why. It's better to let them press it, then show the errors.

The next stand-in models a whole form with these rules: fields with states, a submitted flag, and a visibleError check that implements "invalid and (touched or submitted)". The steps simulate what a user does.

TypeScript Stand-in: states and when errors appear

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Compare the first and last steps: nothing complains on load, the name complains once it was touched while empty, the email complains only after submit (it was dirty but never blurred), and then everything is clean. That is the same experience you build in Angular with touched and submitted.

Reading and resetting the form

NgForm.value is an object keyed by each control's name: { name: 'Ada', email: '[email protected]' }. f.valid and f.invalid summarize all controls, and f.resetForm(value?) clears values and also resets touched, dirty and submitted, which a plain assignment such as model = {...} does not.

ngModel also accepts options: [ngModelOptions]="{ updateOn: 'blur' }" validates when the field loses focus instead of on every keystroke. Note that when a template-driven form first renders, ngModel creates its controls slightly after the first change detection, so code that reads f.value in the constructor sees an empty object; read it in event handlers instead.

When to use template-driven forms

Choose template-driven forms when:

  • the form is small and static: login, search box, newsletter signup;
  • validation is built-in rules only;
  • you want the least TypeScript.

Prefer reactive forms when you need dynamic fields, rules that depend on other fields, async validation, unit tests of form logic without a template, or a typed form model. Both systems share the same underlying FormControl classes, so everything you learn about states carries over. Newer Angular versions are also developing a signal-based option, covered in signal forms.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. An input inside a form has [(ngModel)] but no name attribute. What happens?

    ngModel inside a form registers the control under its name. Without it Angular raises an error, so every ngModel in a form needs a name (or standalone mode).
  2. 2. Which condition best decides whether to show an error message?

    Invalid alone would show errors on a brand-new form. Waiting until the user has left the field or pressed submit is friendlier.
  3. 3. What does the dirty state mean?

    Dirty means the value was changed by the user; touched is about focus leaving the field; invalid is about the rules.
  4. 4. Why call form.resetForm() instead of just assigning a new object to the model?

    Replacing the model changes values but leaves states like touched and submitted. resetForm resets them all, so errors don't flash on the cleared form.
  5. 5. When are reactive forms usually a better fit than template-driven forms?

    Reactive forms give you the model in code, which makes complex, dynamic or heavily tested forms easier. Small static forms are fine template-driven.

Summary

  • Template-driven forms use FormsModule, NgForm on the <form>, and ngModel with a name on each control.
  • Validation comes from attributes (required, minlength, maxlength, min, max, pattern, email); control.errors is null or an object with one key per failed rule.
  • Controls track valid/invalid, touched/untouched and dirty/pristine, mirrored as ng-* CSS classes; the form adds submitted.
  • Show errors when a control is invalid and touched, or after a submit attempt, and connect messages to fields with ARIA attributes.
  • Use resetForm() to clear values and states together, and updateOn: 'blur' to validate later.
  • Great for small, static forms; switch to reactive forms for dynamic, complex or heavily tested ones.
  • The Angular code here is read-only; the validator and form stand-ins model the logic.

Next: Reactive Forms