Best way to propagate data up to parent from 3 levels down


#1

So here’s the problem. I declare a variable in the parent component that is being modified by a nested child component, and I’m getting ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked.

I want to share code, but it’s too much of a mess, and apparently I may not know what I’m doing - so I thought I’d try to talk it through in understanding how to send data back and forth from nested children.

PARENT
    public myVar: number
    justDoIt(someValue) {
        this.myVar = someValue; <-- HOLYSH*T!!! Throws error here.
    }
    CHILD-A
        (updateMyVar)="justDoIt($event)"
        CHILD-1
             (updateMyVarToo)="updateMyVar($event)"

Conceptually, I declare myVar in parent - update it in Child-A by emitting an event this.updateMyVar.emit(newValue), then I have nested component inside that child that affects both Child-A and Parent, by emitting it’s own event with a new value. That error doesn’t get thrown if I remove CHILD-1.

Now, I suppose my tactic was kicking up outputs from child to parent no matter how many levels deep as the only way to do this. What is the correct way to modify a single parent variable from 2 different nested components?


#2

I’m not sure I fully understand the problem. But does the data need to live in the parent component? Could you use a provider for that?


#3

Thanks for responding. That’s not a bad idea at all - storing my data into a central place via provider, and retrieving it per nested component. I did finally resolve my issue, however - in my constructor for CHILD-A, I was calling propagating up the event to CHILD-1 - which initially set the property in parent, then set it again later on, which caused the typescript error.