我在计算TOTAL时遇到问题。虽然它可以工作,但当我尝试删除单行时,值仍然存在。它仍由总数计算。我怎样才能解决这个问题?当我删除单行时,只计算那里的行,为TOTAL计算?这是我的stackblitz代码链接
ngOnInit(){
this.myForm.get('rows').valueChanges.subscribe(values => {
resolvedPromise.then(() => {
this.total = this.totals.reduce((sum, item) => sum + item.total, 0);
});
})
}
onDeleteRow(rowIndex) {
let rows = this.myForm.get('rows') as FormArray;
rows.removeAt(rowIndex)
}
答案 0 :(得分:1)
Yhe问题是,根据“i”的变化,我们可以将属性“material_id”添加到总计并更改函数setOnChange
//When we create the "totals"
//add the property "material_id" to Total
material.materials.forEach(x => {
rows.push(this.fb.group({
...
}))
this.totals.push({amount:0,total:0,material_id:x.id}); //<--add the property material_id
})
//then, in the function setOnChange
setOnChange()
{
const formarray=this.myForm.get('rows') as FormArray;
for (let i=0;i<formarray.length;i++)
{
formarray.at(i).valueChanges.subscribe(val=>{
//search the index of "material_id"
let index=this.totals.findIndex(t=>t.material_id==val.material_id)
if(val.dis_checkbox){
...
this.totals[index].amount=value; //<--NOT this.totals[i],
this.totals[index].total=values;
}
else {
....
this.totals[index].amount=value;
this.totals[index].total=value;
}
});
}
}
答案 1 :(得分:0)
在OnDeleteRow中你有: 1.-删除总数[rowIndex] 2.-重新计算总数
onDeleteRow(rowIndex) {
let rows = this.myForm.get('rows') as FormArray;
rows.removeAt(rowIndex);
this.totals.splice(rowIndex,1); //<--remove the totals[rowIndex]
this.total=this.totals.reduce((sum,item)=>sum+item.total,0); //<--recalculate total
}