Home » Framework » Angular » Create template-driven form and reactive form in angular

Create template-driven form and reactive form in angular

This article explains how to create the template-driven and reactive forms and the differences between both forms in angular applications. Let us see the below things one by one.

  1. What is Form in Angular?
  2. Types of forms in Angular.
  3. Create Template-Driven Form in Angular
  4. Create Reactive Form in Angular
  5. Diferences between the Template-Driven and Reactive Forms.

What is Form in Angular Application?

Forms are used to getting information(inputs) from the users. Many web applications are using the form to handle the user inputs. The example of forms is login, signup, update profile, etc.

Types of Forms in Angular Application

There are two types of Forms available in angular applications. Those are Template-Driven forms and Reactive forms.

Template-Driven Forms

Template-Driven forms are created in the template itself and it does not deal with the component classes. It is very useful to add a simple form like signup, login to the application. It's not more scalable when compared to Reactive Forms.

If we are having the very basic requirements and we can handle the logic within the template then choose the Template-Driven Forms

Reactive Forms

Reactive Forms are explicitly created in the component classes and the validation happens in the component classes themselves. It doesn't rely on template directives. It is more scalable, reusable, and testable than template-driven forms. If the forms are a major module of your application then Reactive Forms is the right choice.

Create Template-Driven Form in Angular Application

First, we have to set up the new angular project by using the below command then let us see how to create forms in that project.

ng new angular-form

The above command creates the new angular project named angular-form. Next, we have to create the component named 'templateDriven' by using the below command.

ng g c templateDriven

Now let us create the template-driven form in this component. For creating the template-driven form we have to import the FormsModule in the below file

app.module.ts

import {  FormsModule  } from '@angular/forms';
imports: [    
    FormsModule 
  ],

Let's do the below changes in the corresponding files of the template-driven component

template-driven.component.html

<h2>Template-Driven Form (ngModel declared with two way data-binding syntax [( )])</h2>
<form #tdForm1="ngForm" (ngSubmit)="tdFormSubmit()">
    <label>First Name</label>
    <input type="text" [(ngModel)]="user.firstName" name="first"  >
    <label>Last Name</label>
    <input type="text" [(ngModel)]="user.lastName" name="last" >
    <label>Gender</label>
    <input type="text" [(ngModel)]="user.gender" name="gender" >
    <button type="submit" >Submit</button>
</form>

template-driven.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-template-driven',
  templateUrl: './template-driven.component.html',
  styleUrls: ['./template-driven.component.css']
})
export class TemplateDrivenComponent implements OnInit {
  constructor() { }
  user = {
    'firstName':'',
    'lastName':'',
    'gender':''
  } 
  ngOnInit(): void {
  }
  tdFormSubmit(){
    console.log(this.user);
  } 
}

We have to add the 'template-driven' component directive like below to see the result in the browser.

app.component.html

<app-template-driven></app-template-driven>

Now save all the changes and run the application using the ng serve command to see the below result in the browser.

angular-template-driven-form-example

In the above example, the ngModel directive is declared with the two-way data binding syntax like [(ngModel)]. Two-way data binding shares the data between the template and its component classes.

So if we change the value of the input box then it also updates the value of the attached property in a component class. So whenever the value changes in the form input the updated value passed in the form submit.

We can also use the one-way data binding syntax to the directive ngModel in the form. But it only submits the form with the initial value, not with the updated value. If we want to get the latest or updated value of the form then we have to pass the form values in the ngSubmit function.

Do the below changes in the corresponding files.

template-driven.component.html

<h2>Template-Driven Form (ngModel declared with one way data-binding syntax)</h2>
<form #tdForm1="ngForm" (ngSubmit)="tdFormSubmit1(tdForm1.value)">
    <label>First Name</label>
    <input type="text" [ngModel]="user1.firstName" name="firstName" >
    <label>Last Name</label>
    <input type="text" [ngModel]="user1.lastName" name="last-name" >
    <label>Gender</label>
    <input type="text" [ngModel]="user1.gender" name="gender-type" >
    <button type="submit" >Submit</button>
</form>

template-driven.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-template-driven',
  templateUrl: './template-driven.component.html',
  styleUrls: ['./template-driven.component.css']
})
export class TemplateDrivenComponent implements OnInit {
  constructor() { }
  user1 = {
    'firstName':'',
    'lastName':'',
    'gender':''
  }
  ngOnInit(): void {
  }
  tdFormSubmit1(userValue:any){
    console.log(userValue);
  }
}

The above code prints the latest form values in the console when clicking the submit button.

We can also use the ngModel directive without data-binding syntax. For this, we don't need to initialize the form control values in the component class. If we want to get the form values then we have to pass that in the ngSubmit function.

Do the below changes in the corresponding files.

template-driven.component.html

<h2>Template-Driven Form (No data-binding and no inialize form values)</h2>
<form #tdForm3="ngForm" (ngSubmit)="tdFormSubmit2(tdForm3.value)">
    <label>First Name</label>
    <input type="text" ngModel name="firstName" >
    <label>Last Name</label>
    <input type="text" ngModel name="lastName" >
    <label>Gender</label>
    <input type="text" ngModel name="gender" >
    <button type="submit" [disabled]="!tdForm3.valid">Submit</button>
</form>

template-driven.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-template-driven',
  templateUrl: './template-driven.component.html',
  styleUrls: ['./template-driven.component.css']
})
export class TemplateDrivenComponent implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }
  tdFormSubmit2(userValue:any){
    console.log(userValue);
  }
}

The above code prints the form control values in the console when clicking the submit button.

Create Reactive Form in Angular Application

First, let us create a component named 'reactive' then we will create a reactive form in that component.

ng g c reactive

The above command creates the component under the app folder named reactive. Now let us create the reactive form by doing the changes in below corresponding files.

For using the reactive form we have to import the ReactiveFormsModule in the app.module.ts file like below.

app.module.ts

import { ReactiveFormsModule } from '@angular/forms';

imports: [    
    ReactiveFormsModule
  ]

reactive.component.html

<h2>Reactice Form Using FormGroup</h2>
<form [formGroup]="reactiveForm" (ngSubmit)="reactiveFormSubmit()">
    <label>First Name</label>
    <input type="text" formControlName="firstName" name="first"  >
    <label>Last Name</label>
    <input type="text" formControlName="lastName" name="last" >
    <label>Gender</label>
    <input type="text" formControlName="gender" name="gender" >
    <button type="submit" [disabled]="!reactiveForm.valid">Submit</button>
</form>

reactive.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder } from '@angular/forms';
@Component({
  selector: 'app-reactive',
  templateUrl: './reactive.component.html',
  styleUrls: ['./reactive.component.css']
})
export class ReactiveComponent implements OnInit {
  constructor(private fb: FormBuilder) { }
  reactiveForm = new FormGroup({
    "firstName": new FormControl(""),
    "lastName": new FormControl(""),
    "gender": new FormControl("")
  });
  ngOnInit(): void {
  }
  reactiveFormSubmit(){
    console.log(this.reactiveForm.value);
  }
}

If we want to see the reactive form in the browser then we have to put the component directive like below.

app.component.html

<app-reactive></app-reactive>
<router-outlet></router-outlet>

Now save all the changes and run the application. You can see the reactive form like below in the browser.

angular-reactive-form-example

In the above reactive form, the form controls are created in the component class itself through the FormControl constructor. The FormGuop groups all the form controls and that keeps the value changes in the form and the validation status of the form.

Finally, in the reactive forms, the form models and the validations are created programmatically in the component class itself and it doesn't rely on the template directives.

Use FormBuilder service in Reactive Forms

We can also use the FormBuilder service to generate the form controls. It avoids the explicit creation of FormGruop and FormControl constructor in the component class. Let us see the example below.

Do the below changes in the corresponding files.

reactive.component.html

<h2>Reactice Form using FormBuilder </h2> 
<form [formGroup]="reactiveForm1" (ngSubmit)="reactiveFormSubmit1()">
    <label>First Name</label>
    <input type="text" formControlName="firstName" name="first">
    <label>Last Name</label>
    <input type="text" formControlName="lastName" name="last" >
    <label>Gender</label>
    <input type="text" formControlName="gender" name="gender" >
    <button type="submit" [disabled]="!reactiveForm1.valid">Submit</button>
</form>

reactive.component.ts

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, FormBuilder } from '@angular/forms';
@Component({
  selector: 'app-reactive',
  templateUrl: './reactive.component.html',
  styleUrls: ['./reactive.component.css']
})
export class ReactiveComponent implements OnInit {
  constructor(private fb: FormBuilder) { }
  reactiveForm1 = this.fb.group({
  "firstName": [""],
  "lastName": [""],
  "gender": [""]
  });
  ngOnInit(): void {
  }
  reactiveFormSubmit1(){
    console.log(this.reactiveForm1.value);
  }
}

Differences between the Template-Driven and Reactive Forms in Angular

Template-Driven FormsReactive Forms
1. It creates the form model implicitly in the template directive.It creates the form model explicitly in the component class.
2. The directive ngModel creates and manages the FormControl instance.The FormControl instance is explicitly created in the component class. The directive [FormControl] in the template links that instance to a specific form element in the view.
3. Do not have programmatic access to the FormControl instance.It manages the FormContral instance and validation status of the form programmatically.
4. Here Template is the source of truth.Here the form model is the source of truth.
5. It is not more scalable when compared to reactive formsIt is more scalable and reusable.
6. Asynchronous data flow between the view and the data model.Synchronous data flow between the view and the data model.

I hope you understood how to create the template-driven and reactive forms and the differences between both forms in the angular application. In the next article let us see how to validate the forms in angular application. Thanks!. Keep Reading!.

Download the full source code from GitHub.

Leave a Reply

Your email address will not be published. Required fields are marked *