Angular FormArray setValue() and patchValue()

Angular FormArray setValue() and patchValue()

The setValue() and patchValue() methods are both used to update the values of controls in a FormArray. However, there are some key differences between the two methods.

setValue

The setValue() method replaces all existing values in the FormArray with the new values that are provided. This means that any existing values in the FormArray will be lost. The setValue() method takes an array of values as an argument. The length of the array must match the length of the FormArray.

patchValue

The patchValue() method only updates the values of the controls that are specified in the object that is provided. Any controls that are not specified in the object will remain unchanged. The patchValue() method takes an object of key-value pairs as an argument. The keys of the object are the names of the controls, and the values of the object are the new values for the controls.

When to use each method

The setValue() method should be used when you want to replace all of the existing values in the FormArray with new values. For example, you might use the setValue() method to initialize the FormArray with values from an API response.

The patchValue() method should be used when you only want to update some of the values in the FormArray. For example, you might use the patchValue() method to update the values of a few controls after the user has entered them into a form.

Here is an example of how to use the setValue() method:

this.formArray.setValue([
  { name: 'John Doe', age: 30 },
  { name: 'Jane Doe', age: 25 }
]);

This code will replace all of the existing values in the FormArray with the two new values that are provided.

Here is an example of how to use the patchValue() method:

this.formArray.patchValue({
  0: { name: 'John Smith' },
  1: { age: 35 }
});

This code will update the name of the first control to "John Smith" and the age of the second control to 35. The values of the other controls in the FormArray will remain unchanged.