我正在嘗試從角度反應形式的 formArray 中洗掉陣列元素,因為我不想顯示空陣列元素。我需要洗掉其所有控制元件都包含空值或 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();
}
}
}
uj5u.com熱心網友回復:
既然你已經掌握了控制權。您可以只訪問該控制元件上的值。
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 才能運行更改檢測。
uj5u.com熱心網友回復:
(<FormArray>this.accounts).controls.forEach((el, i) => {
if(el.value === null || el.value === false) {
(<FormArray>this.accounts.controls).removeAt(i);
}
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/381761.html
上一篇:迭代陣列并替換值
下一篇:根據屬性拆分陣列中的物件
