Difference Between setValue() And patchValue() in Angular

setValue() and patchValue() are two methods of the Angular FormGroup. They both are used to programmatically set the value of the form controls in a form group.

But there is a clear difference between their functionality which is that the setValue() method sets the value of all form controls of a form group while the patchValue() method can set the value of a single, multiple, or all controls of a form group.

Let’s say we have a form group userForm that has two controls userName and email.

this.userForm = this.formBuilder.group({
      userName: new FormControl('', [Validators.required]),
      email: new FormControl('', [Validators.required]),
});

And now, we want to set the value of only one control userName. If you try to set the value of a single control with the setValue() method, it will throw an error.

Therefore, we have to mention all the controls of a form group while setting the form value with the setValue() method.

this.userForm.setValue({
      userName: 'John Doe',
      email: 'john@gmail.com'
});

On the other hand, the patchValue() method does not restrict you to mention all the form controls. It lets you set the value of any individual form control you want.

It means we can set the value of userName without even touching the email field.

The following code will update only the value of the userName. The value of email will be untouched.

this.userForm.patchValue({
      userName: 'John Doe',
});

You can also update the value of all the form controls with the patchValue() method if you want.

As here, we are updating the value of both form controls:

this.userForm.patchValue({
      userName: 'John Doe',
      email: 'johndoe@gmail.com'
});

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.