DEV Community

Ankush Goyal
Ankush Goyal

Posted on

Angular: Reactive Form setValue v/s patchValue

In Angular, setValue() and patchValue() are methods used to update the values of form controls in reactive forms. Here’s when to use each:

setValue()

  • Use When: You need to set all the values for the form controls.
  • Behavior: It requires that the object you pass matches the structure of the form group or form array exactly. If any control is missing, it will throw an error.
  • Example:
  this.form.setValue({
    firstName: 'John',
    lastName: 'Doe',
    age: 30
  });
Enter fullscreen mode Exit fullscreen mode

In this example, the form must have controls for firstName, lastName, and age. If any of these are missing, setValue() will throw an error.

patchValue()

  • Use When: You need to update only some of the values for the form controls.
  • Behavior: It allows you to pass an object with a subset of the form group or form array values. It will only update the specified controls and leave the rest unchanged.
  • Example:
  this.form.patchValue({
    firstName: 'John'
  });
Enter fullscreen mode Exit fullscreen mode

In this example, only the firstName control is updated. The other controls (lastName and age) remain unchanged.

Summary

  • setValue(): Use when you need to set all form controls and the object structure must match the form structure exactly.
  • patchValue(): Use when you need to update only specific form controls and the object structure can be a partial match.

Thank you for reading!
I hope you found this article helpful and informative. If you enjoyed it or learned something new, feel free to share your thoughts in the comments or connect with me.

If you'd like to support my work and help me create more content like this, consider buying me a coffee. Your support means the world and keeps me motivated!

Thanks again for stopping by! 😊

Buy Me A Coffee

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

Cloudinary image

Video API: manage, encode, and optimize for any device, channel or network condition. Deliver branded video experiences in minutes and get deep engagement insights.

Learn more