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
- HTML, CSS, and JS
- Basics of angular
- 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:
- import { Component, OnInit } from '@angular/core';
- import { FormGroup, FormControl, FormControlName } from '@angular/forms';
-
- @Component({
- selector: 'app-test',
- templateUrl: './test.component.html',
- styleUrls: ['./test.component.css']
- })
-
- export class TestComponent implements OnInit {
-
- registrationForm: any;
- graduationData: any;
- pgData: any;
- constructor() { }
-
- ngOnInit() {
- this.graduationData = ['Select','BCA', 'BBA', 'BE', 'B.Tech', 'B.Sc'];
- this.pgData = ['Select','MCA', 'MBA', 'M.Tech', 'M.Sc'];
- this.registrationForm= new FormGroup({
- userName : new FormControl('Irshad'),
- password : new FormControl('password'),
- email : new FormControl('[email protected]'),
- phone : new FormControl('9999999999'),
- address : new FormGroup({
- country : new FormControl('India'),
- state : new FormControl('UP'),
- city : new FormControl('Allahabad'),
- pin : new FormControl('211001')
- }),
- qualification : new FormGroup({
- graduation : new FormControl('BCA'),
- pg : new FormControl('MCA')
- })
- });
- }
- }
Open test.component.html and edit with the below contents
- <div class="container-fluid">
- <h3>Registration Form</h3>
- <form [formGroup]="registrationForm">
- <div class="row">
- <div class="col-sm-6">
- <div class="form-group">
- <label>UserName</label>
- <input formControlName="userName" type="text" class="form-control">
- </div>
- </div>
- <div class="col-sm-6">
- <div class="form-group">
- <label>Password</label>
- <input formControlName="password" type="Password" class="form-control">
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-sm-6">
- <div class="form-group">
- <label>Email Address</label>
- <input formControlName="email" type="email" class="form-control">
- </div>
- </div>
- <div class="col-sm-6">
- <div class="form-group">
- <label>Phone</label>
- <input formControlName="phone" type="Phone" class="form-control">
- </div>
- </div>
- </div>
- <div formGroupName="address">
- <div class="row">
- <div class="col-sm-6">
- <div class="form-group">
- <label>Country</label>
- <input formControlName="country" type="text" class="form-control">
- </div>
- </div>
- <div class="col-sm-6">
- <div class="form-group">
- <label>State</label>
- <input formControlName="state" type="text" class="form-control">
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-sm-6">
- <div class="form-group">
- <label>City</label>
- <input formControlName="city" type="text" class="form-control">
- </div>
- </div>
- <div class="col-sm-6">
- <div class="form-group">
- <label>Pin</label>
- <input formControlName="pin" type="text" class="form-control">
- </div>
- </div>
- </div>
- </div>
- <div formGroupName="qualification">
- <div class="row">
- <div class="col-sm-6">
- <div class="form-group">
- <label>Graduation</label>
- <select formControlName="graduation" class="form-control">
- <option *ngFor="let value of graduationData" [ngValue]="value">{{value}}</option>
- </select>
- </div>
- </div>
- <div class="col-sm-6">
- <div class="form-group">
- <label>PG</label>
- <select formControlName="pg" class="form-control">
- <option *ngFor="let value of pgData" [ngValue]="value">{{value}}</option>
- </select>
- </div>
- </div>
- </div>
- </div>
- <div class="row">
- <div class="col-sm-6">
- <button class="btn btn-primary" type="submit">Register</button>
- </div>
- </div>
- </form>
- {{registrationForm.value | json}}
- </div>
Run the application
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:
- import { Component, OnInit } from '@angular/core';
- import { FormGroup, FormControl, FormControlName } from '@angular/forms';
-
- @Component({
- selector: 'app-test',
- templateUrl: './test.component.html',
- styleUrls: ['./test.component.css']
- })
-
- export class TestComponent implements OnInit {
- registrationForm: any;
- graduationData: any;
- pgData: any;
- sampleData: any;
- constructor() { }
-
- ngOnInit() {
- this.graduationData = ['Select', 'BCA', 'BBA', 'BE', 'B.Tech', 'B.Sc'];
- this.pgData = ['Select', 'MCA', 'MBA', 'M.Tech', 'M.Sc'];
- this.sampleData = {
- userName: 'Irshad',
- password: 'password',
- email: '[email protected]',
- phone: '9999999999',
- address: {
- country: 'India',
- state: 'UP',
- city: 'Allahabad',
- pin: '211001'
- },
- qualification: {
- graduation: 'B.Sc',
- pg: 'MCA'
- }
- };
-
- this.registrationForm = new FormGroup({
- userName: new FormControl(''),
- password: new FormControl(''),
- email: new FormControl(''),
- phone: new FormControl(''),
- address: new FormGroup({
- country: new FormControl(''),
- state: new FormControl(''),
- city: new FormControl(''),
- pin: new FormControl('')
- }),
- qualification: new FormGroup({
- graduation: new FormControl(''),
- pg: new FormControl('')
- })
- });
- setTimeout(() => this.registrationForm.setValue(this.sampleData), 5000);
- }
- }
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:
- this.sampleData = {
- userName: 'Irshad',
- password: 'password',
- email: '[email protected]',
- phone: '9999999999',
- qualification: {
- graduation: 'B.Sc',
- pg: 'MCA'
- }
- };
Now, run the application
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.
- setTimeout(() => this.registrationForm.patchValue(this.sampleData), 5000);
Run the application:
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.