Change Detection Help for Nested Components


#1

I have a parent component that get’s updated at run-time by the child components, which is forcing the ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: ‘NaN’ error. I read through this - Expression has changed after it was checked. Previous value:, and followed link to https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html. I have a better, yet not thorough understanding.

<PARENT>
    totals: number;
    data: load on init from rest api;
    <child-1 [data]="data">update totals when event fired</child-1>
    <child-2 [data]="data">update totals when event fired</child-2>
</PARENT>

I pass down data into each child component once it comes in from an api call. Once the child receives data, it does something with it, and then kicks it back out to parent. The parent then sums that data via the totals property. The problem is, I have many children components that do this asynchronously - so I can now better visualize what’s happening. The value of totals changes after its been checked, over and over again.

After the page initially loads, I don’t get any change detection problems, because its usually a single child component firing an event that updates totals. I don’t get how observables can help with me this issue, and I tried changeDetectionRef.markForCheck() in the function that gets called to update totals every time, but still a problem.

Theoretically, how should i approach this issue of a parent page depending on children components to populate it with data that it both sent in and captured out. Thanks!


#2

Your structure is contrary to the Angular style guide.

https://angular.io/guide/styleguide#delegate-complex-component-logic-to-services

The rule of thumb is that components (including pages) handle DOM rendering only. All interesting logic takes place in providers. It’s hard for me to advise you. I think the way you’ve set things up now is one that will cause performance issues, because your DOM is critically connected with expensive computation. So my advice is: read the Angular style guide, and refactor based on that.

The paradigm I use for Ionic and Angular is that the page is a smart container while the components are dumb containers. That’s more strict than what the style guide recommends, but it plays well with change detection performance.


#3

@ghostrunners was that really your problem for change detection?


#4

Using Providers saves me the headache of managing states in components. To be fair, I’ve been meaning to test drive redux. But yes - passing data back and forth between parent-child components with respect to change detection was my issue.