1

What is the correct way to share a variable between a parent and child container, where the child container is a page set by <router-outlet>?

This post shows the @Input() method, but that method isn't possible (as far as I know) when using <router-outlet>, since you must set a [property] on the HTML element.

Then there is method of using a Service, as answered here, which I have tried, but this doesn't seem to solve my issue, which is this: I get

"ORIGINAL EXCEPTION: Expression has changed after it was checked."

when I change the variable that was put in my Service, because the change is initiated from the child component, and apparently the parent still doesn't 'know' about the change, even though I used the Service technique described in the S.O. post above.

I then tried adding a ChangeDetectorRef to my parent object, and do changeDetector.detectChanges() on the parent whenever the child makes a change to the shared variable. However, this creates an infinite loop, because for some reason the changeDetector calls ngOnInit() of the child (again!), which is one place where the shared variable is changed, which initiates a detectChanges() call from the parent, and on and on it goes.

I could remove this infinite loop, but I'm wondering why detectChanges() on the parent calls the ngOnInit() of the child?!

And, what is the Best Practice for sharing variables between parent and child, where the child is put in the parent page via ng-route? Surely it can't be this difficult!

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.