Home > database >  Angular2 ngOnChanges not firing when input is array
Angular2 ngOnChanges not firing when input is array

Time:11-21

I'm using a ParentComponent that sets inputs to a ChildComponent. If the changed input is number, the ngOnChanges hook fires, but if it's an array, it does not.

Can someone tell me what am I doing wrong, or how to make ngOnChanges firing when the array is changed?

Thank you.

child ts:

export class ChildComponent implements OnInit {
  @Input() num = 0;
  @Input() arr: Array<string> = [];
  constructor() { }

  ngOnInit(): void {
  }

  ngOnChanges() {
    console.log('input changed');
  }

}

parent ts:

export class ParentComponent implements OnInit {

  constructor() { }
  num = 0;
  arr : Array<string> =[];

  ngOnInit(): void {
  }

  changeNumber() {
    this.num = this.num   1;
  }
  changeArray() {
    this.arr.push('some value');
  }

}

parent html:

<button (click)="changeNumber()">change num</button>
<button (click)="changeArray()">change array</button>
<app-child [num]="num" [arr]="arr"></app-child>

CodePudding user response:

ngOnChanges can't detect array changes since the array reference remain as it is even when the content gets changed. instead, you can use a setter method

  private _arr: Array<string> = [];
  @Input() set arr(data) {
    this._arr= data;
    console.log(this._arr);
  };

CodePudding user response:

That's because num is a primitive data type, whereas an array is not. An array is basically an object, where the reference is stored in the variable arr. When you "push" a new entry to the array, the reference itself is not changed.

This is the reason ngOnChange does not fire. If you want to create a new reference to the array and "push" a value to it, you should use the following code:

this.arr = [...this.arr, 'some value'];
  • Related