Reactive Forms - setValue, patchValue And valueChanges

Reactive forms are completely different as compared to the template-driven forms. Here, we will create a form structure before jumping into the HTML code. It helps to separate the component models with the help of controls and group these for easy understanding and targeting to fulfill the specific model operations.

Reactive Forms 

Example - Sample FormGroup,

  1. this.personalForm = this.formBuilder.group({  
  2.     firstName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],  
  3.     lastName: ['', [Validators.required, Validators.minLength(3), Validators.maxLength(8)]],  
  4.     address: ['', [Validators.required]],  
  5.     other: this.formBuilder.group({  
  6.         education: [''],  
  7.         age: [''],  
  8.         gendar: ['male']  
  9.     })  
  10. });  

I’m creating the personal form details without thinking of how HTML code or bindings will work. Once it is ready, simply hook-in to the HTML.

  1. <form class="form-horizontal" [formGroup]="personalForm" (ngSubmit)="onSubmit()">  
  2.    <inputidinputid=”firstName”type=”text”class=”form-control”formControlName=”firstName”>  
  3.    [........]  
  4. </form>  

The complete reference can be referred to from here – https://angular.io/guide/reactive-forms

Demo POC

Below is the sample form with First Name, Address etc. fields – here, I’m trying to add new data and load some data with the help of setValue and patchValue properties of a FormGroup.

 Reactive Forms

On constructor, I have initialized the proper values to all fields.

  1. this.personalForm.setValue({  
  2.     firstName: ’Rajendra’,  
  3.     lastName: ’Taradale’,  
  4.     address: ’Dhanori Pune’,  
  5.     other: {  
  6.         education: ’B C A’,  
  7.         age: 30,  
  8.         gendar: ’male’  
  9.     }  
  10. });  

setValue

The name itself describes that we are setting the new values to all the fields of the form. 

Prerequisites– It’s mandatory to update or provide complete model structure for all fields/form controls within the FormGroup. If you miss any property or subset collections,  then it will throw an exception.

Let’s see the exception case – (I have removed the other subset collection from the FromGroup as I don’t want to update).

Here is the code for setValue click event.
  1. onsetValueClick(): void {  
  2.     this.personalForm.setValue({  
  3.         firstName: ”,  
  4.         lastName: ”,  
  5.         address: ”,  
  6.         // other: {  
  7.         // education: ‘B Tech’,  
  8.         // age: 30,  
  9.         // gendar: ‘male’  
  10.         // }  
  11.     });  
  12. }  

 Reactive Forms

patchValue

Here, patch means updating the form control values partially. In this case, if you miss any property to update, it will not throw an exception.

Now, let us try the same model in using the patchValue method. Here is the click event code.

  1. onpatchValueClick(): void {  
  2.     this.personalForm.patchValue({  
  3.         firstName: ’Rajendra’,  
  4.         lastName: ’Taradale’,  
  5.         address: ”,  
  6.         // other: {  
  7.         // education: ”,  
  8.         // age: ”,  
  9.         // gendar: ”  
  10.         // }  
  11.     });  
  12. }  

Here is a patchValue response – without any error.

Reactive Forms

valueChanges

This property works like an observable as if any value or property changes in a form, it simply triggers that value – like in ASP.NET, we have an event called dropdown change or text box changed. With the help of the valuesChanges event, we can perform the dependent operations as per the user selection or changes.

In this demo, I’m trying to store the complete form data in a console window if any control value changes.

Here, I am editing the last name field – added space and then 1, you can see that it is stored two times - one for space and another one for 1.

Reactive Forms

We can use the valueChanges trigger on FormControl, FormGroup, or SubGroup.

FormControl

  1. this.personalForm.get(‘firstName’).valueChanges.subscribe(  
  2.    value=> {  
  3.       console.log(value);  
  4.    }  
  5. );  
 FormGroup
  1. this.personalForm.valueChanges.subscribe(  
  2.    value=> {  
  3.       console.log(JSON.stringify(value));  
  4.    }  
  5. );  

Subform Group

  1. this.personalForm.get(‘other’).valueChanges.subscribe(  
  2.    value=> {  
  3.       console.log(value);  
  4.    }  
  5. );  
 Reactive Forms