Javascript – Angular 2: How to detect changes in an array? (@input property)

angularjavascripttypescript

I have a parent component that retrieves an array of objects using an ajax request.

This component has two children components: One of them shows the objects in a tree structure and the other one renders its content in a table format. The parent passes the array to their children through an @input property and they display the content properly. Everything as expected.

The problem occurs when you change some field within the objects: the child components are not notified of those changes. Changes are only triggered if you manually reassign the array to its variable.

I'm used to working with Knockout JS and I need to get an effect similar to that of observableArrays.

I've read something about DoCheck but I'm not sure how it works.

Best Answer

OnChanges Lifecycle Hook will trigger only when input property's instance changes.

If you want to check whether an element inside the input array has been added, moved or removed, you can use IterableDiffers inside the DoCheck Lifecycle Hook as follows:

constructor(private iterableDiffers: IterableDiffers) {
    this.iterableDiffer = iterableDiffers.find([]).create(null);
}

ngDoCheck() {
    let changes = this.iterableDiffer.diff(this.inputArray);
    if (changes) {
        console.log('Changes detected!');
    }
}

If you need to detect changes in objects inside an array, you will need to iterate through all elements, and apply KeyValueDiffers for each element. (You can do this in parallel with previous check).

Visit this post for more information: Detect changes in objects inside array in Angular2