setValue() And patchValue() In Angular 2

From angular two with reactive form its very easy to update the form controls value via these two method. Both perform the same operation of setting the value of form control. 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.

this.profileForm = new FormGroup({  
    firstName: new FormControl(''),  
    lastName: new FormControl(''),  
    userName: new FormControl(''),  
    email: new FormControl(''),  
    age: new FormControl('')  


We have the above FormGroup controls. Now, we will use setValue() methods to update all FormControl values. 


As you can see from the above code, setValue() method will set all properties values from model. If you do not mention any of the form control values in model, then it will throw an error exception.

However we can also update specific value using setValue method like below.



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. 


Leave a Reply

Your email address will not be published. Required fields are marked *