删除表单数组元素反应形式角度

问题描述 投票:0回答:3

我正在尝试以角度反应形式从 formArray 中删除数组元素,因为我不想显示空数组元素。我需要删除所有控件都包含 null 值或 false 的元素。我不想删除该元素,即使它的任何控件包含一次指定的值以外的值。

this.accounts 是 formArray。我正在尝试使用 object.keys 但无法检索不包含值的元素

我尝试过以下一些方法。可以吗

  if(this.readonly) {
      for (const control of this.accounts.controls) {
       const result  =  Object.keys(control).find((key) => (control[key] != null || true));
       if(!result) {
       // this.accounts.controls.splice();
       }
      }
    }
angular angular-reactive-forms
3个回答
2
投票

既然你已经拥有了控制权。您只需访问该控件上的值即可。

if(this.readonly) {
   for (const control of this.accounts.controls) {
     const result  =  control.value != null;
     if(!result) {
       // this.accounts.controls.splice();
     }
   }
}

也可以代替 splice()。我建议在 formArray 本身上使用removeAt()。 https://angular.io/api/forms/FormArray#removeat

因为拼接后您还必须调用 updateValueAndValidity 才能运行更改检测。


0
投票
(<FormArray>this.accounts).controls.forEach((el, i) => {
    if(el.value === null || el.value === false) {
(<FormArray>this.accounts.controls).removeAt(i);
 }
})

我们可以运行一个控件循环并检查每个控件的值。由于它是一个表单数组,因此以这种方式在控件上循环不会出现任何问题


0
投票
This is going to clear your whole formarray.

this.form.get('images')['controls'].splice(0,this.form.get('images')['controls'].length);        
© www.soinside.com 2019 - 2024. All rights reserved.