Search code examples
angularangular-formsangular4-formsangular-reactive-forms

Total Not Working In Reactive Forms


I have a problem in calculating the TOTAL. Although it works BUT when i try to remove a single row, the value is still there. It is still calculated by the total. How can i fix this? When i remove a single row, only the rows that are there, is calculated for the TOTAL? Here's my stackblitz code 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)
  }

Solution

  • In OnDeleteRow you have: 1.-Delete the totals[rowIndex] 2.-recalculate total

    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
      }