Angular child component not updating when the parent view updates

3.2k Views Asked by At

So I have some simple synchronous local data shared amongst parent views and that all functions just fine, when the local data changes all the parent views that use it update and reflect correctly.

However when I began splitting my growing project into custom components to prevent code duplication and whatnot things began to get really quirky. The parent still updated normally however the custom component children did not receive any notifications of a change despite the fact that the data is binded. Furthermore it's only the shared data outside of the parent, any changes on the parent itself reflect on the views normally and update as it should.

So as it stands now, when the shared data changes, parts of the parents change and then you have to click the page to trigger a change detection which causes most of the child components to suddenly get the word and update however theres still some that don't get the word so you have to kind of fiddle around on the parent component a bit to get all the views updated which is annoying.

I've tried Tick() and various methods in ChangeDetectorRef and I've tried placing these in various lifecycle phases but I'm at a loss.

Here's a child component on the parent that does not get the update

<does-not-update [(ngModel)]='service.data.1'></does-not-update>

And here's one that does

<input type='number' [(ngModel)]='service.data.2'/>

As stated above, a click on the page is usually enough to kick the children into gear and update.

Theres one component that's a bit more complicated and has 2 children of itself, it passes the ngModel to one child and has that child pass some different data to it's sibling. So it goes like

parent -> child -> grandchild
                       |
                       V
                sibling grandchild

That latter more complicated one especially doesn't work right, a click to the page updates the child and grand child but not the sibling grand child

How do I make sense of this mess?

1

There are 1 best solutions below

0
On

I've faced a similar problem, it's related with Angular's change detection. In my case, I have a parent component (app) with two nested components, table and filter. As the user types in one of filter fields the component emmits a "filterChange" event. The parent component could see the changes in the filter inmediatly, but the table component couldn't see these changes until some event (eg click) ocurrs on him. I've solved this calling detectChanges of ChangeDetectorRef inside the handler of filterChange in the parent component.

 update_filter($filter){
        this.requests_filter = $filter;
        this.cd.detectChanges();
      }