How to patchValue values from FormArray?

I need to patch the value from formArray I first get all values

const control = this.addressPoiForm.get("tableRows") as FormArray;

Second find item which i want to edit(patch)

const item = control.value.filter((valueForm:any) => valueForm.placeId === pin.oldValue.pointId);

item when console.log(item[0]) i got

isEditable: false
latitude: 40.67028015
longitude: -73.85288055
name: "galop"
placeId: 283

I need this item to change. When i try:

item[0].patchValue({
  isEditable: false,
  latitude: pin.drag?.coords.lat,
  longitude: pin.drag?.coords.lng,
  name: pin.oldValue.name,
  placeId: pin.oldValue.pointId,
})

I got error:

core.js:5980 ERROR TypeError: item[0].patchValue is not a function

I am also try with setValue no work… Help how to do this ?

Answer

.value gives you the raw values of the controls in the array. So when you do

const item = control.value.filter((valueForm:any) => valueForm.placeId === pin.oldValue.pointId);

you are actually setting item to an array of the values, not the FormControls. However, .patchValue is a property of a FormControl. You can get the matching control/controls you want by using the .controls property (documentation). It would look something like the following (I renamed some variables to make it more clear):

const arr = this.addressPoiForm.get("tableRows") as FormArray;
const matchingControls = arr.controls.filter((control: FormControl) => control.value.placeId === pin.oldValue.pointId);
matchingControls[0].patchValue({...});

Leave a Reply

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