【问题标题】:problems with ngOnChanges when updating an array更新数组时 ngOnChanges 的问题
【发布时间】:2020-12-22 11:47:01
【问题描述】:

我有一个从另一个组件更新的数组(更新正在发生,字符串被添加到我用测试按钮检查过的数组中)但 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 {
    
  }

}

【问题讨论】:

  • 你有 ChangeDetectionStrategy.OnPush 在这个组件的父组件的某处吗?
  • 这个链接是关于对象这是一个数组
  • 链接中没有提到你提到的策略
  • 第一个评论是别人写的,数组和对象在这方面表现一样

标签: angular typescript lifecycle ngonchanges


【解决方案1】:

您对ngOnChanges 使用了不正确的语法。使用以下内容:

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

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

.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>

【讨论】:

  • 请更改任何内容
  • 只是提到我应用的更改是 array.push()
  • 你从哪里应用这个array.push()?
  • 来自更新此输入的父组件...无论如何我决定放弃数组并且它有效!但很高兴了解我应该如何完成这项工作
  • 我已经包含了更多的解释和一个例子,希望对您有所帮助!
猜你喜欢
  • 1970-01-01
  • 2021-08-07
  • 2017-09-30
  • 2020-09-28
  • 1970-01-01
  • 2016-01-09
  • 1970-01-01
  • 2017-01-10
  • 2019-08-24
相关资源
最近更新 更多