更新数组时 ngOnChanges 的问题

问题描述

我有一个正在从另一个组件更新的数组(更新正在发生并且字符串被添加到我已经使用测试按钮检查过的数组中)但 ngOnChanges 不会检测到任何更改。我的代码有什么问题?

我应用的更改是 array.push()。

import { Component,OnInit,Input,OnChanges } from '@angular/core';
import {MatAccordion} from '@angular/material/expansion';

@Component({
  selector: 'app-cart',templateUrl: './cart.component.html',styleUrls: ['./cart.component.css']
})
export class CartComponent implements OnInit,OnChanges {
  totalPrice = 0;
  constructor() { }
  @input() Products: Array<String>;

  ngOnChanges() {
    console.log(this.Products)
  }

  ngOnInit(): void {
    
  }

}

解决方法

您对 ngOnChanges 使用了错误的语法。使用以下内容:

ngOnChanges(changes: SimpleChanges) {
   console.log(changes.Products.currentValue);
}

另外,请注意,除非对数组的引用发生变化,否则上述生命周期钩子不会被触发。如果您希望触发生命周期挂钩,则每次将元素推送到数组时更改引用。例如:

.ts

myArr = [];

add() {
  this.myArr = [...this.myArr,String(Math.random())];
  console.log(this.myArr)
}

.html

<button (click)="add()">Add more numbers</button>

<app-cart-component [Products]="myArr"></app-cart-component>