I'm using angular for developing eCommerce app. I'm Using OnChange lifecycle hook to detect changes in the cart component and calculate total price. However, changes are not being detected.
Typescript Code:
import { ChangeDetectionStrategy, Component, Input, OnChanges, SimpleChanges } from '@angular/core';
import { Device } from '../../shared/Device.model';
@Component({
selector: 'app-cart-calculator',
changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './cart-calculator.component.html',
styleUrls: ['./cart-calculator.component.scss']
})
export class CartCalculatorComponent implements OnChanges {
@Input() cartProducts: Device[];
@Input() quantities: number[];
constructor() { }
totalPrice: number = 0;
ngOnInit(): void {
}
ngOnChanges() {
this.totalPrice = 0;
for (let i = 0; i < this.cartProducts.length; i++) {
this.totalPrice += this.cartProducts[i].devicePrice * this.quantities[i];
console.log(this.quantities);
}
}
}
Template part:
<app-cart-calculator [quantities]="quantities" [cartProducts]="cartDevices"></app-cart-calculator>
Array is an object in javascript so you have to pass new array every time you want it to be detected by ngOnChanges(). So for eg:- you pushed a new value to array like :-
after that you need to give it a new reference :-