Search code examples
javascriptarraysangulartypescriptangular-changedetection

Which is the best way to track changes in an array inside a component?


When creating a custom component in Angular 7, which is the best way to track changes in an array?

Example:

export class Test {
   @Input() myArray = []

 // tell if array was modified (push, pop, reassigned...)
}

Also, is there a better way to do this (like observables, etc)? Why?


Solution

  • I would do it using ngOnChanges() which is one of the Angular lifecycle hook. Where you can find information like:

    1. If it is the first change.
    2. What's the current value.
    3. What's the previous value.

    It is of type : SimpleChange

    ngOnChanges(changes: SimpleChanges){
     // Detect Changes
      let myArrayChange = changes['myArray'];
      let currentValue = myArrayChange.currentValue;
      let previousValue = myArrayChange.previousValue;
    }
    

    Also, Angular change detection only checks object identity, not object content, so push, pop are not detected. So what you can do is in the Child Component where you are assigning this input, while pushing, push different object by using slice() method of Array

    Child Component HTML:

    <test myArray="arr"></test>
    

    Child Component TS:

    export class Child{
    
        arr: any = [];
    
        someMethod(){
            this.arr.push('new element');
            this.arr = this.arr.slice();
        }
    }