SetValue & PatchValue in FormArray Angular

Learn how to use SetValue & PatchValue in FormArray in Angular. We use these methods to set the values of the form in Reactive Forms. These methods are available in the AngularFormsModule. Refer to the guide on how to use the SetValue & PatchValue in Angular Forms. But setting the value of the form controls, when we have nested FormArray becomes a little tricky.

Nested FormArray Example

We built the nested Form array in the last tutorial. The code is as shown below. You can refer to the tutorial nested FormArray Example for the explanation of the code

The following is the structure of our form model. There can be many teachers and each teacher can manage many batches. Each batch can contain several students.

app.component.html

app.component.ts

Form in Action

How to load initial data in FormArray

When the form is loads for the first time, it will not have any controls in the FormArray. Calling PatchValue or SetValue will have no effect.

The patchValue1 method in the following example tries to load the data. The data contains one teacher managing two batches with three students in each batch.

Invoke the method from the template.

As you can see from below patchValue won’t work unless we have all the controls loaded. Hence we need to build the form manually before calling patchValue

Example of PatchValue in FormArray

PatchValue Example

To load the data, we need to update our form programmatically to match the data. The patchValue2 method in the following example does that.

We start by clearing the FormArray. The clearing is useful if the user wants to discard and reload the original data again.

To clear the form, all You need to do is get hold of the top-level formArray and call clear method Note that clear is available from Angular 8+. If you are using the prior versions, then use the removeAt(index) method

Now loop through the data

For every teacher create a nested form array and push it to the top-level formArray

Now, loop through the batches and add it to the batches form array

Next, do the same for students

Now, our form model matches the data structure. You can now call patchValue or setValue to update the Form. Remember the difference between PatchValue & SetValue.

  1. The patchValue sets the data, even when data does not match the structure of the Form.
  2. SetValue requires that the data must match the structure of the FormArray exactly

You can read about them from the tutorial SetValue & PatchValue in Angular

Summary

This guide demonstrated how to update the values of FormArray using the initial data. To do that first you need to update your form to match the structure of the data. Then make use of the either PatchValue or SetValue

2 thoughts on “SetValue & PatchValue in FormArray Angular”

Leave a Comment

Your email address will not be published.

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

Scroll to Top