Difference Between setValue() And patchValue() In Angular 2

In this blog, I will explain the difference between setValue() and patchValue() which are frequently used in Angular2 reactive forms. 
 
Updating Form controls from a model is very easy and flexible in Reactive Form API of Angular v2. So, setValue() and patchValue() are the methods by which we can update the Reactive forms controls from our model. Let us see the difference between these two in the following example.
 
setValue()
 
setValue() will set the value of all form controls of the form group.  
  1. this.profileForm = new FormGroup({  
  2.   
  3. FirstName: new FormControl(''),  
  4. LastName: new FormControl(''),  
  5. UserName: new FormControl(''),  
  6. Email: new FormControl(''),  
  7. MobileNumber: new FormControl('')  
  8.   
  9. })   
  10.    
We have the above FormGroup controls. Now, we will use setValue() methods to update all FormControl values. 
  1. profileForm.setValue({  
  2. "FirstName":"Ajay",  
  3. "LastName":"Panda",  
  4. "UserName":"ajay33",  
  5. "Email":"[email protected]",  
  6. "MobileNumber":"8745212589"  
  7. });   
As you can see from the above code, setValue() method will set all fromcontrol values from model. If you do not mention any of the formcontrol values in model, then it will throw an exception.
 
patchValue() 

patchValue() method will also set Formcontrol values from a model but only for those which we have mentioned in the model. So,  it is not necessary to pass all the model info in patchValue() method. 
  1. profileForm.patchValue({    
  2. "FirstName":"Ajay",    
  3. "LastName":"Panda"  
  4. });   
As you can see from the above code, I am only passing two properties to my formgroup control, so patchValue() will set these two properties in form. Unlike to setValue(), it is not necessary to pass all models, we can only pass required models to the from group control.