Angular-根据匹配条件从forEach循环中的FormArray中移除FormGroup



我有下面的代码

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

我不确定代码是否正确,但是它没有被执行。基本上,我需要从formGroups数组中删除attributeDisplayName为空的所有对象/formGroup。

item.value为我提供了attributeDisplayName所在的具有属性的当前对象。请提出建议。谢谢

'removeAt'是从FormArray中删除单个对象/控件的正确方法,但如果在循环中与多个控件一起使用,则会删除一些控件,而不会删除其他控件。

这种情况可能是由于从您正在循环的同一索引中删除而发生的,为了克服这一点,您可以首先识别不需要的控件,然后反向删除它们。

Stackblitz示例

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

}

这将清除整个formarray。

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

最新更新