0

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.

2 Answers 2

3

'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);
});

}

Sign up to request clarification or add additional context in comments.

Comments

0

This is going to clear your whole formarray.

this.form.get('images')['controls'].splice(0,this.form.get('images')['controls'].length);        

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.