Getter not returning the right values

I am trying to sum up all of my sub totals and return a grand total but I get wild values and I used to get the error: Expression has changed after it was checked.

When I use

import { ChangeDetectionStrategy } from '@angular/core';
@Component({
changeDetection: ChangeDetectionStrategy.OnPush
})

it suppresses the expression has changed error but I still get wild values for the grand total.

This is in my component:

totals : number[ ] = [ ];

get grandTotal() {

let i;
let sub_total = 0;
let grand_total = 0;
if  (this.isSubmitted == true){
sub_total = this.product_price * this.quantity;

if (typeof this.product_price  === "undefined") {
return 0;
} else {
this.totals.push(sub_total);
for (i = 0; i < this.totals.length; i++) {
 grand_total += this.totals[i];
this.isSubmitted = false;
}
return grand_total;
}
}
}

This is in my HTML;

<div>Grand Total {{ grandTotal }}</div>

The first submission works but then after that the grand total updates before the form is submitted. The isSubmitted variable must have been changed to true even though the form only submitted once. How can I prevent the isSubmitted variable from remaining true?

I was able to fix this by setting this.isSubmitted = false; in my getter.

3 Likes