← Back to Angular, page 3

angular-0057 · Easy fresher

How do template-driven forms work with ngModel, and how do you show validation errors?

In a template-driven form each input uses ngModel with a name attribute, and Angular creates the form model behind the scenes. A template reference such as #email="ngModel" exposes the control state (valid, touched, errors), and HTML validators such as required and minlength become Angular validators.

Full answer

Template-driven forms keep the setup in the template. You need FormsModule in imports.

How it works:

  1. <form #f="ngForm" (ngSubmit)="save(f)">. The NgForm directive attaches automatically to a form tag and collects all controls inside it.
  2. <input name="email" [(ngModel)]="user.email" required email #email="ngModel">. ngModel registers the input as a control, and the name attribute is required inside a form, since it becomes the control's key.
  3. HTML attributes required, minlength, maxlength, pattern, and email activate matching Angular validators.
  4. #email="ngModel" exports the control into a template variable, so you can read email.invalid, email.touched, and email.errors.

Showing errors only after the user touched the field avoids red text at the start: @if (email.invalid && email.touched) { ... }. After a failed submit you can show all errors by checking f.submitted.

[(ngModel)] is two-way binding, that is [ngModel] plus (ngModelChange). Updates happen asynchronously, so values are not available in the same tick as the first render.

When to choose it: simple forms (login, a search box, a feedback form). The limits: validation rules live in HTML and are harder to unit test, dynamic fields are awkward, and cross-field rules need a directive. For anything larger, use reactive forms.

Typed values: ngModel is not typed, so user should be a typed object in the class.

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

interface Feedback {
  email: string;
  message: string;
}

@Component({
  selector: 'app-feedback-form',
  imports: [FormsModule],
  template: `
    <form #f="ngForm" (ngSubmit)="send(f)">
      <label for="email">Email</label>
      <input id="email" name="email" type="email" required email [(ngModel)]="model.email" #email="ngModel" />
      @if (email.invalid && (email.touched || f.submitted)) {
        <small role="alert">
          @if (email.errors?.['required']) { Email is required. }
          @else { Enter a valid email address. }
        </small>
      }

      <label for="message">Message</label>
      <textarea id="message" name="message" required minlength="10" [(ngModel)]="model.message" #message="ngModel"></textarea>
      @if (message.invalid && (message.touched || f.submitted)) {
        <small role="alert">Write at least 10 characters.</small>
      }

      <button type="submit" [disabled]="f.invalid">Send</button>
    </form>
  `,
})
export class FeedbackFormComponent {
  model: Feedback = { email: '', message: '' };

  send(form: NgForm): void {
    if (form.invalid) {
      return;
    }
    console.log('Sending', this.model);
    form.resetForm();
  }
}

Angular 20.3, strict template check passes. The submit button stays disabled until the form is valid.

Key points

  • Import `FormsModule`. Inputs need `ngModel` and a `name` inside a form.
  • `#ref="ngModel"` exposes `valid`, `touched`, and `errors` to the template.
  • HTML attributes like `required` and `minlength` act as validators.
  • Good for small forms. Use reactive forms for complex ones.

Common mistakes

  • Forgetting the `name` attribute, which causes the error that `ngModel` needs a name when inside a form.
  • Showing errors before the user has typed anything.
  • Trying to unit test complex validation through the template.

Follow-ups

  • What does `#f="ngForm"` give you?
  • How is `[(ngModel)]` expanded?
  • How would you add a custom validator to a template-driven input?

Tips

  • Give the sizing rule: small forms here, large forms reactive.
  • Mention touched versus dirty when showing messages.
  • Show the `name` attribute rule. It is the first thing that breaks in practice.

Evaluation rubric

  • Explains NgForm, ngModel, and template variables.
  • Shows validation with touched state.
  • States limits compared with reactive forms.