我正在使用 Angular 开发电子商务应用程序。我正在使用 OnChange 生命周期挂钩来检测购物车组件中的更改并计算总价。但是,未检测到更改。
打字稿代码:
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);
}
}
}
模板部分:
<app-cart-calculator [quantities]="quantities" [cartProducts]="cartDevices"></app-cart-calculator>