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)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay