3

I'm using an array of objects which I'm passing from my parent component to child components. When a new item is pushed to the array or the property of one of the existing objects in the array changes it does not trigger the ngOnChanges for the components that are using this variable (parent/child/sibling components).

In AngularJS we had $watchCollection using which we could keep watch on the complex objects. Do we have something similar for Angular2+?

How to do deep checking similar to $watchCollection in Angular2 +?

I'm familiar with AngularJS but not Angular2 +.

UPDATE:
Following @Shirish Patel's suggestion here, I found that although the change in the variable gets reflected everywhere but the ngOnChanges function does not get triggered. Why is it so? I need to get this function triggered so that I can handle other operations on change of the value.

Temp O'rary
  • 5,366
  • 13
  • 49
  • 109
  • 1
    this [stackoverflow lin](https://stackoverflow.com/questions/43223582/why-angular-2-ngonchanges-not-responding-to-input-array-push)k might help you. – Shirish Patel Oct 26 '17 at 12:02

1 Answers1

0

Dont push objects to your array as mutating things will not trigger ngOnChanges lifecycle hook. Sort of like rxjs distinctUntilChanged, needs a new array not a modified one.

You need to provide the inputs a new version of your array try:

this.array = [...this.array, itemWhichNeedsAdding]

The above returns an new instance of an array and will trigger change detection.

rtn
  • 2,012
  • 4
  • 21
  • 39