0

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?

cfr
  • 135
  • 1
  • 1
  • 9
  • Do you just want to run a function each time it's changed? the `ngOnChanges` lifecycle method might be what you're looking for. – pjlamb12 May 17 '19 at 19:15
  • I think ngOnChanges tracks the array reference . It works if I do something like `array = [ 'test' ].concat(array)` but not if I do a simple `array.push('test');` – cfr May 17 '19 at 19:37

1 Answers1

1

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();
    }
}
Koushik Ravulapelli
  • 1,140
  • 11
  • 30