Open In App

Reactive Forms vs Template Driven Forms

Angular provides two main approaches for handling forms: Reactive Forms and Template-Driven Forms. In this article, we'll learn more about Reactive Forms and Template-Driven Forms in detail.

Reactive Forms

Reactive Forms is a way through which we can build forms in Angular. It makes use of the component class to programmatically declare the form controls. The validations and other form controls are written in the component class. Then these written form controls are then bound to the input fields present in the html template.

Syntax:

import { FormBuilder, FormGroup, FormControl } from '@angular/forms';

// Create form controls and group them into a form group
const form = new FormGroup({
username: new FormControl(''),
email: new FormControl(''),
password: new FormControl('')
});

Features of Reactive Forms:

Example:

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

<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
  <div>
    hello
    <label for="username">Username:</label>
    <input type="text" id="username" formControlName="username" />
    <div
      *ngIf="myForm.get('username').invalid && myForm.get('username').touched"
    >
      <small *ngIf="myForm.get('username').errors.required"
        >Username is required.</small
      >
    </div>
  </div>
  <div>
    <label for="email">Email:</label>
    <input type="email" id="email" formControlName="email" />
    <div *ngIf="myForm.get('email').invalid && myForm.get('email').touched">
      <small *ngIf="myForm.get('email').errors.required"
        >Email is required.</small
      >
      <small *ngIf="myForm.get('email').errors.email"
        >Invalid email format.</small
      >
    </div>
  </div>
  <div>
    <label for="password">Password:</label>
    <input type="password" id="password" formControlName="password" />
    <div
      *ngIf="myForm.get('password').invalid && myForm.get('password').touched"
    >
      <small *ngIf="myForm.get('password').errors.required"
        >Password is required.</small
      >
    </div>
  </div>
  <button type="submit" [disabled]="myForm.invalid">Submit</button>
</form>
// app.component.ts

import { Component } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
})
export class AppComponent {
    myForm: FormGroup;

    constructor() {
        this.myForm = new FormGroup({
            username: new FormControl('', Validators.required),
            email: new FormControl('', [Validators.required, Validators.email]),
            password: new FormControl('', Validators.required),
        });
    }

    onSubmit() {
        if (this.myForm.valid) {
            console.log(this.myForm.value);
        }
    }
}

export class MyFormComponent { }
// app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { JitCompilerFactory } from '@angular/platform-browser-dynamic';

@NgModule({
    imports: [BrowserModule, FormsModule, ReactiveFormsModule],
    declarations: [AppComponent, HelloComponent],
    bootstrap: [AppComponent],
    providers: [],
})
export class AppModule { }

Output:

Reactive Forms

After Submitting Button is clicked

Template Driven Forms

Template Driven Forms is the most simplest way through which we can build a form in Angular. It utilizes Angular's two-way data binding directive (ngModel). This helps the user to manage and create the form instance. The whole form is managed entirely in the view template. There is no or minimal need to write programmatically code in the typescript file.

Syntax:

<form #form="ngForm" (ngSubmit)="onSubmit(form)">
<input type="text" name="username" [(ngModel)]="model.username" required>
<input type="email" name="email" [(ngModel)]="model.email" required email>
<input type="password" name="password" [(ngModel)]="model.password" required>
<button type="submit">Submit</button>
</form>

Features of Template Driven Forms:

Example:

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

<form (ngSubmit)="onSubmit()">
  <div>
    <label for="username">Username:</label>
    <input
      type="text"
      id="username"
      name="username"
      [(ngModel)]="userData.username"
      required
    />
  </div>
  <div>
    <label for="email">Email:</label>
    <input
      type="email"
      id="email"
      name="email"
      [(ngModel)]="userData.email"
      required
      email
    />
  </div>
  <button type="submit">Submit</button>
</form>
// app.component.ts

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

@Component({
    selector: 'my-app',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
})
export class AppComponent {
    userData = {
        username: '',
        email: '',
    };

    onSubmit() {
        console.log(this.userData);
    }
}

export class MyFormComponent { }
// app.module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { JitCompilerFactory } from '@angular/platform-browser-dynamic';

@NgModule({
    imports: [BrowserModule, FormsModule, ReactiveFormsModule],
    declarations: [AppComponent, HelloComponent],
    bootstrap: [AppComponent],
    providers: [],
})
export class AppModule { }

Output:

Template Driven Forms

Difference between Reactive Forms and Template Driven Forms

Aspect

Reactive Forms

Template Driven Forms

Data Binding

Data Binding is done using formControlName and formGroup.

Data Binding is done using ngModel directive.

Form Creation

Form is created programmatically. We need to write more code in component.

Form is created automatically from the template. There is less requirement to write code in component.

Programming paradigm

The logic of the form mainly resides in the template.

The logic of the form is mainly defined in the template.

Complexity Handling

It is more suited for complex forms and dynamic form elements.

It is more suitable for simpler forms.

Validation

The validation logic are defined in the component code.

The validation is provided with the help of template directives.

Flexibility

There is more flexibility for handling complex and complicated usecases.

There is less flexibility for handling complex and complicated usecases.

Integration with backend

It is easier to integrate with the backend.

It is more difficult to integrate with the backend.

Form Grouping

There is proper grouping of form controls.

There is no proper grouping of form controls.

Conclusion

In Summary, we can conclude that there are two ways through which we can build forms in Angular. Template Driven forms is the easier and simplest method to build forms in Angular. It makes use of directives to control the component state and logic. While Reactive form is more complex way to build forms in Angular. It is used to build forms of more complex data management and logic.

Article Tags :