0

I'm taking @Input() from parent component, and using ngOnChanges to catch the change. But it only fires once. It changes the current value, but the previous value is always undefined. Here's what I'm doing:

myArray=[];
ngOnChanges(changes:SimpleChanges):void{
  console.log(changes);
  if(changes.myInput.currentValue != undefined && changes.myInput.currentValue != changes.myInput.previousValue){
    for(var i=0;i<this.changes.myInput.currentValue.length;i++){
    console.log("length is" , i);
    this.myArray.push(this.changes.myInput.currentValue);
    }
  }
}

Here, console.log(changes) occurs only once. Although the value inside it changes every time @Input() changes. My myInput.currentValue is an array and I want to do something every time a new object is pushed on to the array via @Input() from parent. It doesn't go inside the if condition and I can't find length.

4

1 回答 1

1

我的 myInput.currentValue 是一个数组,每次通过父级的 @Input() 将新对象推送到数组时,我都想做一些事情。

这就是问题的原因。输入的值(所以,引用)在技术上并没有改变——对象发生了变异,但引用保持不变——并且变化检测机制错过了它。所以不要做这样的事情

myArray.push(newValue);

在父母中,改为

myArray = [...myArray, newValue];
于 2020-06-18T10:47:44.967 回答