Angular 2 set value vs patch value in FormGroup

Asked on June 17, 2017
What is difference between Angular 2 set value and patch value in FormGroup?

Replied on June 17, 2017
Angular FormGroup has methods such as setValue() and patchValue(). setValue() and patchValue() both sets the value in form control of FormGroup.  setValue() sets the value in each and every form control of FormGroup. We cannot omit any form control in setValue() but when we want to assign only few form controls of FormGroup then we need to  use patchValue(). Both methods are used in the same way.

Suppose we have FormGroup instance.

userForm = new FormGroup({
     name: new FormControl(),
     age: new FormControl()

1. Using setValue()

this.userForm.setValue({name: 'Mahesh', age: '20' });

It is necessary to mention all from controls in setValue() otherwise it will throw error. 

2. Using patchValue()

this.userForm.patchValue({name: 'Mahesh'}); 

When we use patchValue() then it is not necessary to mention all form controls.

Find the link

Write Answer

©2024 | Privacy Policy | Contact Us