Open In App

Template Driven Form vs Reactive Form in Angular.

Angular provides two main approaches for creating forms: Template-Driven Forms and Reactive Forms. In this article, we'll see both methods, highlighting their features, and providing code examples. We'll also compare them side by side to help you understand when to use each.

Template-Driven Form

Template-driven forms are built around HTML-driven components. They rely heavily on directives in the template to handle form validation and data submission. As the name suggests, in Template-Driven Form, the form logic is mainly in the template file. It uses Angular's "ngModel" two-way data-binding directive to create and manage the underlying form instance.

Syntax:

<form #myForm="ngForm" (ngSubmit)="onSubmit(myForm)">
<input name="name" ngModel required>
<button type="submit">Submit</button>
</form>

Features of Template-Driven Forms

Example:

Create a new project with the help of Angalur cli.

ng new forms
<!-- app.component.html -->

<h3>Complex Template Driven Form</h3>
<form #userForm="ngForm" (ngSubmit)="onSubmit(userForm.value)">
  <div>
    <label for="name">Name: </label>
    <input
      type="text"
      id="name"
      name="name"
      [(ngModel)]="credentials.name"
      required
    />
  </div>
  <div>
    <label for="email">Email: </label>
    <input
      type="email"
      id="email"
      name="email"
      [(ngModel)]="credentials.email"
      required
      email
    />
  </div>
  <div>
    <label for="password">Password: </label>
    <input
      type="password"
      id="password"
      name="password"
      [(ngModel)]="credentials.password"
      required
    />
  </div>
  <button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>
//app.component.ts

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

@Component({
  selector: 'app-tdf-complex',
  standalone: true,
  imports: [FormsModule],
  templateUrl: './tdf-complex.component.html',
  styleUrl: './tdf-complex.component.css',
})
export class TdfComplexComponent {
  credentials: any = {};

  onSubmit(formValue: any) {
    console.log('Form value: ', formValue);
  }
}

Output:

ctdf

Reactive Forms

In Reactive Forms, the validation logics and control are kept separated from the view template. These are managed programmatically in the component class using FormBuilder, FormGroup, FormControl, and FormArray. The template is only responsible for the basic structure of the form. This helps in scalability and maintainability if the form logic becomes too complex. Reactive Forms gives more control to the developers with regards to form state, validation, and form value changes.

Syntax:

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<input formControlName="name" required>
<button type="submit">Submit</button>
</form>

Features of Reactive Forms:

Example:

<!-- app.component.html -->

<h3>Complex Template Driven Form</h3>
<form [formGroup]="userForm" (ngSubmit)="onSubmit()">
  <div>
    <label for="name2">Name: </label
    ><input type="text" id="name2" formControlName="name" />
  </div>
  <div>
    <label for="email2">Email: </label
    ><input type="email" id="email2" formControlName="email" />
  </div>
  <div>
    <label for="password2">Password: </label
    ><input type="password" id="password2" formControlName="password" />
  </div>
  <button type="submit" [disabled]="userForm.invalid">Submit</button>
</form>
// app.component.ts
import { Component } from '@angular/core';
import {
  FormControl,
  FormGroup,
  ReactiveFormsModule,
  Validators,
} from '@angular/forms';

@Component({
  selector: 'app-reactive-complex',
  standalone: true,
  imports: [ReactiveFormsModule],
  templateUrl: './reactive-complex.component.html',
  styleUrl: './reactive-complex.component.css',
})
export class ReactiveComplexComponent {
  userForm = new FormGroup({
    name: new FormControl('', [Validators.required]),
    email: new FormControl('', [Validators.required, Validators.email]),
    password: new FormControl('', [Validators.required]),
  });

  onSubmit() {
    console.log(this.userForm.value);
  }
}

Output:

crf

Difference between Template-Driven Form and Reactive Form


Template-Driven Form (TDF)

Reactive Form

Form model setup

Implicit in nature, as it relies on directives in the template to create and manipulate the underlying object model.

Explicit in nature, as it provides direct access to the underlying form's object model.

Logic handling

Form logic is mostly handled in the template.

Form logic is handled in the component.

Data flow

Two-way data binding with NgModel directive provides asynchronous data update between view and model.

Data flow between view and model is synchronous in nature as each form element in the view is directly linked to the form model with the help of a FormControl instance.

Form validation

Validations are done with the help of directives.

Validations are done with the help of functions.

Unit testing

Tight coupling between the template and the component provides limited testability of form logic.

Separation of concern between the view and model provides better testability of form logic.

Conclusion

Angular provides two approaches for building forms. On one hand, we have Template-Driven Form with its simple and familier syntax and simple learning curve, making it the go to choice for simple forms and rapid prototyping. If your form does not have complex logic and validations, which could be managed from within the template along with validation attributes integrated with HTML, then you should definitely go with Template-Driven approach.

On the other hand, there is Reactive Form which has a steeper learning curve, along with a comparatively verbose code structure. Having said that, it is still the way to go if your form requirement has complex logic along with nested groups that require complex validation logic. Since all these are handled separately in the component file, rather than in the template, it offers better maintainability, testability, and flexibility for handling complex form scenarios.

Article Tags :