【问题标题】:ngOnchange doesn't detect dynamic changesngOnchange 不检测动态变化
【发布时间】:2021-03-29 06:29:38
【问题描述】:

我正在使用 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>

【问题讨论】:

  • html 是什么?

标签: angular e-commerce ngonchanges


【解决方案1】:

Array 是 javascript 中的一个对象,因此每次您希望 ngOnChanges() 检测到新数组时都必须传递新数组。因此,例如:-您将新值推送到数组中,例如:-

       arr.push(4);

之后你需要给它一个新的参考:-

 arr = [...arr];

【讨论】:

  • 我通过检测数组长度的变化解决了。
【解决方案2】:

您需要将SimpleChanges 参数添加到OnChanges 的实现(ngOnChanges)中。

ngOnChanges(changes: SimpleChanges) {      
  this.totalPrice = 0;
  const products = changes['cartProducts'] && changes['cartProducts'].currentValue;
  this.totalPrice = products.reduce((totalPrice, product) => totalPrice + (product.quantity * product.devicePrice), 0);
}

您也有引用问题,您正在改变 组件中的属性 cartDevices,而不是重新分配其值。

【讨论】:

    猜你喜欢
    • 2022-12-22
    • 1970-01-01
    • 2020-05-30
    • 1970-01-01
    • 2017-06-07
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多