FormBuilder Service in Angular

Introduction

 
In Angular applications, we use Reactive forms to create the form modal for our angular application. Creating forms using FormGroup and FormControl is very repetitive as we create the instances of group and FormControl manually every time we create the new fields or group.
 
So to avoid this multiple repetitive process Angular provides a helper service which in turn provides methods in generating forms controls. We will create the forms controls just like the previous generation of new FormControls but in less code.
 
FormBuilder is a service, so we have to import the service and inject it into the constructor. 
 

Implementation 

 
Let us create a simple application that utilizes Reactive forms.
Create a TestApp project using Angular CLI.
Create a test component which will contain the forms and related field.
 
Open test.component.ts and add the below contents:
  1. import { Component, OnInit } from '@angular/core';  
  2. import { FormBuilder } from '@angular/forms';  
  3.   
  4. @Component({  
  5.   selector: 'app-test',  
  6.   templateUrl: './test.component.html',  
  7.   styleUrls: ['./test.component.css']  
  8. })  
  9. export class TestComponent implements OnInit {  
  10.   
  11.   registrationForm: any;  
  12.   graduationData: any;  
  13.   pgData: any;  
  14.   sampleData: any;  
  15.   constructor(private fb: FormBuilder) {  
  16.     this.registrationForm = this.fb.group({  
  17.       userName: ['Irshad'],  
  18.       password: ['password'],  
  19.       email: ['[email protected]'],  
  20.       phone: ['9999999999'],  
  21.       address: this.fb.group({  
  22.         country: ['India'],  
  23.         state: ['UP'],  
  24.         city: ['Allahabad'],  
  25.         pin: ['211001']  
  26.       }),  
  27.       qualification: this.fb.group({  
  28.         graduation: ['BCA'],  
  29.         pg: ['MCA']  
  30.       })  
  31.     });  
  32.    }  
  33.   
  34.   ngOnInit() {  
  35.     this.graduationData = ['Select''BCA''BBA''BE''B.Tech''B.Sc'];  
  36.     this.pgData = ['Select''MCA''MBA''M.Tech''M.Sc'];  
  37.   }  
  38. }  
Open test.component.html and edit with below contents:
  1. <div class="container-fluid">  
  2.     <h3>Registration Form</h3>  
  3.     <form [formGroup]="registrationForm">  
  4.         <div class="row">  
  5.             <div class="col-sm-6">  
  6.                 <div class="form-group">  
  7.                     <label>UserName</label>  
  8.                     <input formControlName="userName" type="text" class="form-control">  
  9.                 </div>  
  10.             </div>  
  11.             <div class="col-sm-6">  
  12.                 <div class="form-group">  
  13.                     <label>Password</label>  
  14.                     <input formControlName="password" type="Password" class="form-control">  
  15.                 </div>  
  16.             </div>  
  17.         </div>  
  18.         <div class="row">  
  19.             <div class="col-sm-6">  
  20.                 <div class="form-group">  
  21.                     <label>Email Address</label>  
  22.                     <input formControlName="email" type="email" class="form-control">  
  23.                 </div>  
  24.             </div>  
  25.             <div class="col-sm-6">  
  26.                 <div class="form-group">  
  27.                     <label>Phone</label>  
  28.                     <input formControlName="phone" type="Phone" class="form-control">  
  29.                 </div>  
  30.             </div>  
  31.         </div>  
  32.         <div formGroupName="address">  
  33.             <div class="row">  
  34.                 <div class="col-sm-6">  
  35.                     <div class="form-group">  
  36.                         <label>Country</label>  
  37.                         <input formControlName="country" type="text" class="form-control">  
  38.                     </div>  
  39.                 </div>  
  40.                 <div class="col-sm-6">  
  41.                     <div class="form-group">  
  42.                         <label>State</label>  
  43.                         <input formControlName="state" type="text" class="form-control">  
  44.                     </div>  
  45.                 </div>  
  46.             </div>  
  47.             <div class="row">  
  48.                 <div class="col-sm-6">  
  49.                     <div class="form-group">  
  50.                         <label>City</label>  
  51.                         <input formControlName="city" type="text" class="form-control">  
  52.                     </div>  
  53.                 </div>  
  54.                 <div class="col-sm-6">  
  55.                     <div class="form-group">  
  56.                         <label>Pin</label>  
  57.                         <input formControlName="pin" type="text" class="form-control">  
  58.                     </div>  
  59.                 </div>  
  60.             </div>  
  61.         </div>  
  62. <div formGroupName="qualification">  
  63.     <div class="row">  
  64.         <div class="col-sm-6">  
  65.             <div class="form-group">  
  66.                 <label>Graduation</label>  
  67.                 <select formControlName="graduation" class="form-control">  
  68.                     <option *ngFor="let value of graduationData" [ngValue]="value">{{value}}</option>  
  69.                 </select>  
  70.             </div>  
  71.         </div>  
  72.         <div class="col-sm-6">  
  73.             <div class="form-group">  
  74.                 <label>PG</label>  
  75.                 <select formControlName="pg" class="form-control">  
  76.                     <option *ngFor="let value of pgData" [ngValue]="value">{{value}}</option>  
  77.                 </select>  
  78.             </div>  
  79.         </div>  
  80.     </div>  
  81. </div>  
  82. <div class="row">  
  83.     <div class="col-sm-6">  
  84.         <button class="btn btn-primary" type="submit">Register</button>  
  85.     </div>  
  86. </div>  
  87. </form>  
  88. {{registrationForm.value | json}}  
  89. </div>  
Run the application:
 
form-builder-angular 
 
You can see the form has been created and values are filled that we have given as default. 
 
Using setValue and patchValue methods: 
 
Open test.component.ts and edit with below contents:
  1. import { Component, OnInit } from '@angular/core';  
  2. import { FormBuilder } from '@angular/forms';  
  3.   
  4. @Component({  
  5.   selector: 'app-test',  
  6.   templateUrl: './test.component.html',  
  7.   styleUrls: ['./test.component.css']  
  8. })  
  9.   
  10. export class TestComponent implements OnInit {  
  11.   registrationForm: any;  
  12.   graduationData: any;  
  13.   pgData: any;  
  14.   sampleData: any;  
  15.   constructor(private fb: FormBuilder) {  
  16.     this.registrationForm = this.fb.group({  
  17.       userName: [''],  
  18.       password: [''],  
  19.       email: [''],  
  20.       phone: [''],  
  21.       address: this.fb.group({  
  22.         country: [''],  
  23.         state: [''],  
  24.         city: [''],  
  25.         pin: ['']  
  26.       }),  
  27.       qualification: this.fb.group({  
  28.         graduation: [''],  
  29.         pg: ['']  
  30.       })  
  31.     });  
  32.    }  
  33.   
  34.   ngOnInit() {  
  35.     this.graduationData = ['Select''BCA''BBA''BE''B.Tech''B.Sc'];  
  36.     this.pgData = ['Select''MCA''MBA''M.Tech''M.Sc'];  
  37.     this.sampleData = {  
  38.       userName: 'Irshad',  
  39.       password: 'password',  
  40.       email: '[email protected]',  
  41.       phone: '9999999999',  
  42.       address: {  
  43.         country: 'India',  
  44.         state: 'UP',  
  45.         city: 'Allahabad',  
  46.         pin: '211001'   
  47.       },  
  48.       qualification: {  
  49.         graduation: 'B.Sc',  
  50.         pg: 'MCA'  
  51.       }  
  52.     };  
  53.     setTimeout(() => this.registrationForm.setValue(this.sampleData), 5000);  
  54.   }  
  55. }  
Run the application and after 5 seconds the sampleData values will be set to the form controls. setValue will work same whether we use formBuilder service or not. It will throw an error if any field is not passed in its control mapping. So we have to follow its strict rule by providing all the properties that is going to match its controls.
 
Open test.component.ts and change the setTimeout statement by replacing setValue to patchValue. 
  1. setTimeout(() => this.registrationForm.patchValue(this.sampleData), 5000);  
Now you can skip giving any field control value from the sampleData object. It will not throw error and set the values that are available.
 
So the sampleData  
  1. this.sampleData = {  
  2.       userName: 'Irshad',  
  3.       password: 'password',  
  4.       email: '[email protected]',  
  5.       phone: '9999999999'        
  6.     };  
Is correct in case of patchValue but incorrect in case of setValue method.\
 
Also if we are giving the sampleData as below:
  1. this.sampleData = {  
  2.       firstName: 'Mohammad',  
  3.       lastName: 'Irshad',  
  4.       userName: 'Irshad',  
  5.       fullName: 'Mohammad Irshad',  
  6.       password: 'password',  
  7.       email: '[email protected]',  
  8.       phone: '9999999999'        
  9.     };  
This will be correct in the case of patchValue method. Doesn’t matter if we supply the values (firstName, lastName, fullName) that are not there in the formGroup.
 
But it will throw an error in case of setValue by giving an error message that ‘firstName’ control is not found.
 

Summary 

 
In this article, we learned about FormBuilder Service in Angular and how to use these services in the code examples.