Template-Driven vs. Reactive Forms

Kasun Weerasinghe
4 min readAug 15, 2024

--

Mastering Angular (Part III)

Introduction

Forms are a fundamental part of web applications, enabling users to input and submit data. Angular provides two powerful ways to work with forms: template-driven and reactive forms. Understanding the differences between these two approaches and knowing when to use each can help you build more efficient and maintainable applications. In this article, we’ll explore the key differences, discuss when to use each type, and provide practical examples.

Differences Between Template-Driven and Reactive Forms

Template-Driven Forms

Template-driven forms rely heavily on Angular’s data-binding capabilities and are defined in the template (HTML). They are straightforward to set up and are more suitable for simple forms.

Key Characteristics:

  • Declarative: Form controls are defined directly in the template using directives like ngModel.
  • Simplicity: Easier to set up and understand for smaller, simple forms.
  • Two-Way Data Binding: Automatically keeps the form model and the view in sync using ngModel.
<!-- app.component.html -->
<form #form="ngForm" (ngSubmit)="onSubmit(form)">
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" ngModel>
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" ngModel>
</div>
<button type="submit">Submit</button>
</form>
// app.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
onSubmit(form: any) {
console.log('Form Data:', form.value);
}
}

Reactive Forms

Reactive forms are more structured and robust, making them suitable for complex forms with dynamic behavior. They are defined in the component class, giving you greater control over the form’s behavior and validation.

Key Characteristics:

  • Programmatic: Form controls are defined in the component class, not in the template.
  • Scalability: Better suited for larger and more complex forms.
  • Immutable Data: Uses immutable data structures, making it easier to track changes and manage form state.
<!-- app.component.html -->
<form [formGroup]="form" (ngSubmit)="onSubmit()">
<div>
<label for="name">Name:</label>
<input type="text" id="name" formControlName="name">
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" formControlName="email">
</div>
<button type="submit">Submit</button>
</form>
// app.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
form: FormGroup;

ngOnInit() {
this.form = new FormGroup({
name: new FormControl('', Validators.required),
email: new FormControl('', [Validators.required, Validators.email])
});
}

onSubmit() {
console.log('Form Data:', this.form.value);
}
}

When to Use Template-Driven Forms

Template-driven forms are ideal for simpler forms with basic validation needs. They are easy to set up and understand, making them a good choice for:

  • Small to medium-sized forms.
  • Forms with straightforward validation requirements.
  • Quick prototyping and simple data entry forms.

When to Use Reactive Forms

Reactive forms are better suited for complex and dynamic forms that require more control and scalability. They are ideal for:

  • Large forms with complex validation logic.
  • Forms that require dynamic creation or removal of controls.
  • Scenarios where you need to react to form changes programmatically.
  • Applications requiring a more structured and maintainable form architecture.

Example: Login Form (Template-Driven)

A simple login form is a perfect example of when to use template-driven forms. It involves basic validation and straightforward data binding.

<!-- login.component.html -->
<form #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm)">
<div>
<label for="username">Username:</label>
<input type="text" id="username" name="username" ngModel required>
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" ngModel required>
</div>
<button type="submit">Login</button>
</form>
// login.component.ts
import { Component } from '@angular/core';

@Component({
selector: 'app-login',
templateUrl: './login.component.html'
})
export class LoginComponent {
onSubmit(form: any) {
console.log('Login Data:', form.value);
}
}

Example: Dynamic Survey Form (Reactive)

A dynamic survey form where questions can be added or removed is an example of when to use reactive forms. It involves complex validation and dynamic form control creation.

<!-- survey.component.html -->
<form [formGroup]="surveyForm" (ngSubmit)="onSubmit()">
<div formArrayName="questions">
<div *ngFor="let question of questions.controls; let i = index">
<label [for]="'question' + i">Question {{ i + 1 }}:</label>
<input [id]="'question' + i" [formControlName]="i">
</div>
</div>
<button type="button" (click)="addQuestion()">Add Question</button>
<button type="submit">Submit Survey</button>
</form>
// survey.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormArray, FormControl } from '@angular/forms';

@Component({
selector: 'app-survey',
templateUrl: './survey.component.html'
})
export class SurveyComponent implements OnInit {
surveyForm: FormGroup;

ngOnInit() {
this.surveyForm = new FormGroup({
questions: new FormArray([])
});
}

get questions() {
return this.surveyForm.get('questions') as FormArray;
}

addQuestion() {
this.questions.push(new FormControl(''));
}

onSubmit() {
console.log('Survey Data:', this.surveyForm.value);
}
}

Understanding the differences between template-driven and reactive forms in Angular can help you choose the right approach for your application. Template-driven forms are simple and quick to set up, making them ideal for basic forms, while reactive forms offer more control and flexibility for complex scenarios.

--

--

Kasun Weerasinghe
Kasun Weerasinghe

Written by Kasun Weerasinghe

Hi there! 👋 I'm Kasun, Front-End Developer. With a deep love for technology and innovation.

No responses yet