Managing Control Values in Angular Forms

Introduction

 
In this article we will see how we can update the values of form controls programmatically. For setting the values from component class we will use setValue method of Reactive forms. We can set the default values from the forms controls constructor, or we can have the object of values that we can set to the form controls.
 

Prerequisites

  1. HTML, CSS, and JS
  2. Basics of angular
  3. Reactive Forms

Implementation

 
Let us create a simple application that utilizes the 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 { FormGroup, FormControl, FormControlName } from '@angular/forms';   
  3.    
  4. @Component({   
  5.   selector: 'app-test',   
  6.   templateUrl: './test.component.html',   
  7.   styleUrls: ['./test.component.css']   
  8. })  
  9.   
  10. exportclass TestComponent implements OnInit {   
  11.    
  12.   registrationForm: any;   
  13.   graduationData: any;   
  14.   pgData: any;   
  15.   constructor() { }   
  16.      
  17.   ngOnInit() {   
  18.   this.graduationData = ['Select','BCA', 'BBA', 'BE', 'B.Tech', 'B.Sc'];   
  19.   this.pgData = ['Select','MCA', 'MBA', 'M.Tech', 'M.Sc'];   
  20.     this.registrationForm= new FormGroup({   
  21.      userName : new FormControl('Irshad'),   
  22.      password : new FormControl('password'),   
  23.      email : new FormControl('[email protected]'),   
  24.      phone : new FormControl('9999999999'),   
  25.      address : new FormGroup({   
  26.        country : new FormControl('India'),   
  27.        state : new FormControl('UP'),   
  28.        city : new FormControl('Allahabad'),   
  29.        pin : new FormControl('211001')   
  30.      }),   
  31.      qualification : new FormGroup({   
  32.        graduation : new FormControl('BCA'),   
  33.        pg : new FormControl('MCA')   
  34.      })   
  35.    });   
  36.   }   
  37. }  
Open test.component.html and edit with the 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
image1
 
You can see the values are being set as default that we have set in form controls in component class.
 
setValue method:
 
We have the formGroup “registrationForm” and we need to set the values of the form group programmatically. 
 
The setValue method accept the object that need to match the structure of the formGroup with the proper control names as the keys and the corresponding given value.
 
Let us create an exact structure of the registrationForm group and apply that object values to the form controls. 
 
Open test.component.ts and edit with below contents: 
  1. import { Component, OnInit } from '@angular/core';   
  2. import { FormGroup, FormControl, FormControlName } from '@angular/forms';   
  3.   
  4. @Component({   
  5.   selector: 'app-test',   
  6.   templateUrl: './test.component.html',   
  7.   styleUrls: ['./test.component.css']   
  8. })   
  9.   
  10. exportclass TestComponent implements OnInit {   
  11.   registrationForm: any;   
  12.   graduationData: any;   
  13.   pgData: any;   
  14.   sampleData: any;   
  15.   constructor() { }   
  16.    
  17.   ngOnInit() {   
  18.     this.graduationData = ['Select', 'BCA', 'BBA', 'BE', 'B.Tech', 'B.Sc'];   
  19.     this.pgData = ['Select', 'MCA', 'MBA', 'M.Tech', 'M.Sc'];   
  20.     this.sampleData = {   
  21.       userName: 'Irshad',   
  22.       password: 'password',   
  23.       email: '[email protected]',   
  24.       phone: '9999999999',   
  25.       address: {   
  26.         country: 'India',   
  27.         state: 'UP',   
  28.         city: 'Allahabad',   
  29.         pin: '211001'   
  30.       },   
  31.       qualification: {   
  32.         graduation: 'B.Sc',   
  33.         pg: 'MCA'   
  34.       }   
  35.     };   
  36.    
  37.     this.registrationForm = new FormGroup({   
  38.       userName: new FormControl(''),   
  39.       password: new FormControl(''),   
  40.       email: new FormControl(''),   
  41.       phone: new FormControl(''),   
  42.       address: new FormGroup({   
  43.         country: new FormControl(''),   
  44.         state: new FormControl(''),   
  45.         city: new FormControl(''),   
  46.         pin: new FormControl('')   
  47.       }),   
  48.       qualification: new FormGroup({   
  49.         graduation: new FormControl(''),   
  50.         pg: new FormControl('')   
  51.       })   
  52.     });   
  53.     setTimeout(() => this.registrationForm.setValue(this.sampleData), 5000);   
  54.   }   
  55. }  
What we have done is we have just created a sampleData object with exactly same set of properties that are required to set to the registrationForm formGroup. Or we can say that setValue method accepts the object that matches the structure of the formGroup with formControl names as keys
 
Run the application and wait for 5 seconds the default sampleData will be set that we have given to the setValue method. 
 
Now let us suppose we don’t want to set the address fields. Then the sampleData will be as below: 
  1. this.sampleData = {   
  2.       userName: 'Irshad',   
  3.       password: 'password',   
  4.       email: '[email protected]',   
  5.       phone: '9999999999',   
  6.       qualification: {   
  7.         graduation: 'B.Sc',   
  8.         pg: 'MCA'   
  9.       }   
  10.     };  
     
Now, run the application
 
image2 
 
You can see the value will not be set to the formControls and if you open the console you can see the above error. 
 
So, setValue is very strict for maintaining the structure of the formGroup, you have to pass all the formControl values. 
 
Still if you want to set the partial values to the formGroup then you can use patchValue method. 
 
Now change the statement setValue to patchValue. Remaining all will be same. 
  1. setTimeout(() => this.registrationForm.patchValue(this.sampleData), 5000);  
     
Run the application:
 
image3 
 
You can see the values for address fields are not set and only the partial form is being filled whose values are supplied.
 
Thank you. 


Similar Articles