formarray patchvalue at index

Understanding FormArray patchValue() at Index

As a web developer, I have worked with Angular Forms many times. One of the requirements while working with forms is to update the form values dynamically. The FormArray is a powerful feature in Angular Forms that helps us manage an array of form controls. We can use the patchValue() method to update the value of a form control or a group of controls at a specific index in the FormArray.

Syntax


formArray.patchValue(value: any[], options?: {
    onlySelf?: boolean;
    emitEvent?: boolean;
    emitModelToViewChange?: boolean;
    emitViewToModelChange?: boolean;
  }): void

The patchValue() method takes an array of values that need to be updated and an optional object of options like onlySelf, emitEvent, emitModelToViewChange, and emitViewToModelChange.

Example

Suppose we have a FormArray that contains two form groups - 'name' and 'email'. We want to update the value of the 'name' control at index 0. We can use patchValue() method to achieve this:


const formArray = new FormArray([
  new FormGroup({
    name: new FormControl('John Doe'),
    email: new FormControl('[email protected]')
  }),
  new FormGroup({
    name: new FormControl('Jane Doe'),
    email: new FormControl('[email protected]')
  })
]);

formArray.patchValue([
  {
    name: 'New Name'
  }
], { onlySelf: true });

Here, we are passing an array of one object that contains the updated value for the 'name' control of the first form group. We are also passing an options object with onlySelf set to true, which means only the FormArray instance will be updated, and not its parent.

Multiple Ways to Update FormArray

The patchValue() method is not the only way to update a FormArray in Angular Forms. We can also use setValue() method, which takes an array of values for all controls in the FormArray, and updateValueAndValidity() method, which updates the value and validation status of a control. However, patchValue() is the preferred method when we only want to update a few values in a FormArray.

Conclusion

In conclusion, patchValue() method is a powerful and convenient way to update the value of a control or a group of controls at a specific index in a FormArray. It provides us with flexibility and control while managing form values in Angular Forms.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe