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 Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay