javascriptangulartypescriptngonchanges

ngOnChanges fires only for the first time


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.


Solution

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

    And here's the cause of the problem. The input's value (so, reference) doesn't technically change - the object gets mutated, but the reference stays the same - and the change detection mechanism misses it. So instead of doing something like this

    myArray.push(newValue);
    

    in the parent, do instead

    myArray = [...myArray, newValue];