Grand Totals Not Updating Upon Delete

I am using a getter to update the grand totals. When I click on the deleteItem button, the grand total isn’t updated and the table cell displays the same grand total as before even though items have been removed. How can I fix this?

In the HTML:

<form name="yourForm" [formGroup]="yourForm">
<table>
<tr *ngFor="let item of items; let i = index">
<td><td></td>
<button type="button" (click)="deleteItem(i)" class="deletebtn">X</button></td>
<td>{{item.quantity}} </td>
<td>{{item.product_price }} </td>
<td>{{item.quantity * item.product_price }}</td>
</tr>
<tr><td></td><td></td><td><b>Grand Total</b> </td><td><b>{{grandTotal }}</b></td></tr>
</table>

In the component:

  totals = [];
  get grandTotal() {
    let i;
    let sub_total = 0;
    let grand_total = 0;
    if (this.isSubmitted == true) {
      if (
        typeof this.product_price !== "undefined" &&
        typeof this.quantity !== "undefined"
      ) {
        sub_total = this.product_price * this.quantity;
        this.totals.push(sub_total);
      }
    }

    for (i = 0; i < this.totals.length; i++) {
      grand_total += this.totals[i];
    }
    this.isSubmitted = false;
    return grand_total;
  }

  deleteItem(i) {
    this.totals = [];
 this.isSubmitted = true;
    this.grandTotal;
    this.items.splice(i, 1);
    this.setStorageItems(this.items);
   
  }

Shouldn’t this.grandTotal; be
this.grandTotal = this.getGrandTotal();
?

Thanks for the suggestion, jenovs. The function is grandTotal() and not getGrandTotal() and when I add it to my code, I get the errors: Cannot assign to ‘grandTotal’ because it is a read-only property and this expression is not callable Type ‘Number’ has no call signatures.

Ah, ok. The formatting threw me off :slightly_smiling_face:

Try to replace

this.items.splice(i,1);

with

this.items = this.items.filter((_, j) => j !== i);

I added that and now it updates the grand total with the price that has just been deleted. It doesn’t work.

It does the same thing that splice does.

No, it doesn’t. Splice changes the array in place, filter creates new array.

Maybe you could create a working example in https://codesandbox.io/ ?