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