SetValue & PatchValue in Angular

In this tutorial, we will learn how to set the model values in Reactive Forms. It is done using the setValue and patchValue methods provided by the AngularFormsModule. In this post, we will learn more about setValue and patchValue and also learn the difference between them. We also learn about the onlySelf & emitEvent arguments with an example.

Angular Forms

The Angular has two ways to build the forms. One using the Template-driven approach & the other one is the reactive forms approach. We covered both in our previous tutorial. The list of all tutorials on Angular forms is here.

  1. Angular Forms Tutorial: Fundamental & Concepts
  2. Template Driven Forms in Angular
  3. Set Value in Template Driven forms in Angular
  4. Reactive Forms in Angular
  5. FormBuilder in Reactive Forms
  6. SetValue & PatchValue in Angular
  7. StatusChanges in Angular Forms
  8. ValueChanges in Angular Forms
  9. FormControl
  10. FormGroup
  11. FormArray Example
  12. Build Dynamic or Nested Forms using FormArray
  13. Validations in Reactive Forms in Angular
  14. Custom Validator in Reactive Forms
  15. Passing Parameter to Custom Validator in Reactive Forms
  16. Inject Service into Custom Validator
  17. Validation in Template Driven Forms
  18. Custom Validator in Template Driven Forms

The Angular Forms has three main building blocks i.e FormControl, FormGroup & FormArray. All these components have methods setValue & patchValue and behave differently

SetValue

setValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

We use the SetValue to update the FormControl , FormGroup or FormArray. When we use it to update the FormGroup or FormArray the SetValue requires that the object must match the structure of the FormGroup or FormArray exactly. Otherwise, it will result in an error.

PatchValue

patchValue(value: { [key: string]: any; }, options: { onlySelf?: boolean; emitEvent?: boolean; } = {}): void

The PatchValue is used to update only a subset of the elements of the FormGroup or FormArray. It will only update the matching objects and ignores the rest.

onlySelf

The Angular checks the validation status of the form, whenever there is a change in value. The validation starts from the control whose value was changed and propagates to the top level FormGroup. This is the default behavior

There may be circumstances, where you do not want angular to check the validity of the entire form, whenever you change the value using the setValue or patchValue. We do that by setting the onlySelf=true as the argument. In such cases, the angular only checks the validity of the current control, but does not check any other control and does not propagate the validity checking to the parent form group.

emitEvent

The Angular forms emit two events. One is ValueChanges & the other one is StatusChanges. The ValueChanges event is emitted whenever the value of the form is changed. The StatusChanges event is emitted whenever angular calculates the validation status of the Form. This is the default behavior

We can stop that from happening, by setting the emitEvent=false

SetValue Vs PatchValue

The difference is that with setValue we must include all the controls, while with the patchValue you can exclude some controls.

Example form setup

Create a new angular application. Import both FormsModule, ReactiveFormsModule from @angular/forms. Also add it into the imports metadata

Create two new components reactive.component.ts & template-component.ts with their respective templates. Also, update the app.component.ts & its template as shown below

[tabby title=”app.component.ts”]

[tabby title=”app.component.html”]

[tabbyending]

SetValue & PatchValue in Reactive Forms

Here is our template-component.ts & template-component.html.

[tabby title=”reactive-component.ts”]

[tabby title=”reactive-component.html”]

[tabbyending]

Setting Initial /Default Value

There are two ways, in which set the initial value. One at the time of defining the Form Model as the first argument to the FormControl as shown below

Another option is to use the setValue in ngOnInit method. To do that, first, create a contact object with the properties exactly matching the Form Model and then invoke the setValue as shown below

The advantageous of the second option is that you can call the setDefault any time and set the default values again.

As said earlier, the setValue only works, when the properties match exactly. If you remove any of the properties or add a new property, then it will result in an error.

Ex: if you comment out isMarried field, then you will see the following error in the console window.

Or if you add a new property surname, you will see the following error.

Nested FormGroup

As mentioned earlier, the setValue updates the entire FormGroup. Hence we can update the nested form group separately.

In the following example, we get the reference to the address form group and then invoke the setValue to update only the address.

Here again, the properties of the address must match completely. Otherwise, it will result in an error.

FormControl

The value of individual control can be easily set

PatchValue

We use patchValue when we want to update only the subset of properties.

For Example, the following shows how to update only city & street properties using the patchValue method.

Reset Form

OnlySelf Example

The angular forms calculate the validity status of the form, whenever the values of any of the controls on the form change. The validation check starts from the control and is run for the parent control until it reaches the top-level FormGroup.

We can use the onlySelf:true argument to tell angular not to run validation on the parent control.

For Example, we have added a required validator to the firstname FormControl. Now enter some text in the firstname field to make the form Valid and then set the value to blank as shown below. The Form becomes invalid.

Make the form valid again by entering some text in the firstname field. Now, try the same with onlySelf:true added. The Form stays Valid.

emitEvent example

The Angular forms emit two events. One is ValueChanges & the Other one is statusChanges. You can stop them from happening using the emitEvent:false argument as shown below.

First, subscribe to statusChanges & valueChanges event at Form Level and also at the control level.

And then change the value of the firstname and you will see all the four events are fired.

And when you use the emitEvent:false the events are suppressed.

SetValue & PatchValue in Template-driven Forms

You can make use of the setValue & patchValue in template-driven forms also. We learned how to do it in set Value in template-driven forms in the angular tutorial.

To do that, we first need the reference to the Form model in the template, using the viewchild

Once, we have the reference, you can make use of SetValue & PatchValue as shown in the following examples. For a more detailed explanation refer to the tutorial Set Value in template-driven forms in the angular

[tabby title=”template-component.ts”]

[tabby title=”template-component.html”]

[tabbyending]

Summary

In this tutorial, we learned how to use setValue & pathcValue to set the values of the Reactive forms in Angular.

Here is the list of all tutorials in Angular Forms

  1. Angular Forms Tutorial: Fundamental & Concepts
  2. Template Driven Forms in Angular
  3. Set Value in Template Driven forms in Angular
  4. Reactive Forms in Angular
  5. FormBuilder in Reactive Forms
  6. SetValue & PatchValue in Angular
  7. StatusChanges in Angular Forms
  8. ValueChanges in Angular Forms
  9. FormControl
  10. FormGroup
  11. FormArray Example
  12. Build Dynamic or Nested Forms using FormArray
  13. Validations in Reactive Forms in Angular
  14. Custom Validator in Reactive Forms
  15. Passing Parameter to Custom Validator in Reactive Forms
  16. Inject Service into Custom Validator
  17. Validation in Template Driven Forms
  18. Custom Validator in Template Driven Forms

4 thoughts on “SetValue & PatchValue in Angular”

  1. venkat subramaniyam

    u missed out defining the app-routing.module.ts

    const routes: Routes = [
    { path: ‘reactive’, component: ReactiveComponent },
    { path: ‘template’, component: TemplateComponent },
    ];

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top