总计不以反应形式工作

Total Not Working In Reactive Forms

我在计算总计时遇到问题。尽管当我尝试删除单行时它有效,但该值仍然存在。还是按总数计算。我怎样才能解决这个问题?当我删除一行时,只有存在的行才计算总计?这是我的 stackblitz 代码 link

CODE LINK HERE

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

在 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
  }

问题在于,变化取决于 "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;
         }
        });
      }
   }