How to use template-driven forms in Angular

Template-driven forms provide a declarative approach to form handling in Angular, where form structure and validation are defined directly in the template. As the creator of CoreUI, a widely used open-source UI library, and with over 25 years of experience in software development including Angular since 2014, I’ve found template-driven forms ideal for simple forms with straightforward validation requirements. The most effective approach is using ngModel with template reference variables to create forms with minimal component code. This method is perfect for rapid prototyping and simple form scenarios where reactive forms might be overkill.

Use ngModel with template reference variables to create declarative forms with built-in validation support.

import { Component } from '@angular/core'

@Component({
  selector: 'app-contact-form',
  template: `
    <form #contactForm="ngForm" (ngSubmit)="onSubmit(contactForm)">
      <input
        name="name"
        ngModel
        #name="ngModel"
        required
        placeholder="Name">
      <div *ngIf="name.invalid && name.touched">Name is required</div>

      <input
        name="email"
        ngModel
        #email="ngModel"
        required
        email
        placeholder="Email">
      <div *ngIf="email.invalid && email.touched">Valid email is required</div>

      <button type="submit" [disabled]="contactForm.invalid">Submit</button>
    </form>
  `
})
export class ContactFormComponent {
  onSubmit(form: any) {
    if (form.valid) {
      console.log(form.value)
    }
  }
}

Template-driven forms use ngModel to create two-way data binding and template reference variables to access form and control state. The form validation is handled through HTML5 attributes like required and email, with Angular providing additional validation states like invalid, touched, and dirty. The entire form state is accessible through the template reference variable assigned to ngForm.

Best Practice Note:

This is the approach we use in CoreUI Angular components for simple forms like contact forms and basic user input. While template-driven forms are easier to set up, consider reactive forms for complex validation logic, dynamic form controls, or when you need extensive testing capabilities.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author