Home > other >  Angular - Remove FormGroup from FormArray in forEach loop based on matching criteria
Angular - Remove FormGroup from FormArray in forEach loop based on matching criteria

Time:12-17

I have below code

    (this.formGroups.get('items') as FormArray).controls.forEach((item, index, object) => {
        console.log(item.value.attributeDisplayName);
        if (item.value.attributeDisplayName === '') {
            object.splice(index, 1);
        }
    });

I am not sure whether the code is correct or not, however it is not getting executed. Basically I need to remove all the object(s)/formGroup(s) from my formGroups array where attributeDisplayName is empty.

item.value gives me the current object with properties where attributeDisplayName resides. Please suggest. Thanks.

CodePudding user response:

'removeAt' is the proper way of removing single object/control from a FormArray, but if you use it with multiple controls in loop it results in removing some but not others.

This might be happening due to removing from the same index you are looping over, to overcome this you can first identify the unwanted controls and then remove them in reverse.

Stackblitz example

deleteEmpty() {
let indexToRemove: number[] = [];

let fromArray = this.form.get('items') as FormArray;
fromArray.controls.forEach((control, index) => {
  if (!control.value.attributeDisplayName) {
    indexToRemove.push(index);
  }
});
indexToRemove.reverse().forEach((index) => {
  fromArray.removeAt(index);
});

}

  • Related