How can I access a grandchild component? For example, I have a grandparent.component.ts, parent.component.ts, and child.component.ts. The child.component.ts has a list of buttons in its template. The parent.component.ts contains the child.component.ts. The grandparent.component.ts contains the parent.component.ts. I want to disable the buttons in the child.component.ts in the grandparent.component.ts. How do I do this?
1 Answers
I would do this with a service. The service would:
- expose an observable that emits when controls should be disabled/enabled
- expose a function that should be called to make the observable emit
The order of events, for grandparent to disable grandchild's controls would be:
- grandchild subscribes to observable
onInit - grandparent calls the function
- function causes observable to emit
- grandchild receives the emission, and disables/enables its controls
In asnwer to your comment, here are two alternatives that I would not recommend
You could use
@Input()in parent component and data binding in the grandparent template to pass a value from grandparent to parent, and use the same mechanism --@Input()in child and databinding in parent template -- to pass the parent's databound property to the child.grandparent could write a value to the
windowobject since all components can see it. eg:window.enableControls = false. Child could have asetIntervalorObservable.intervalthat reads that value every 500 milliseconds and updates child controls. Clear the interval when the child component is destroyed or you'll have a memory leak.
Again, I would not recommend either option, but they would work.
ChildComponentnot by passing to theParentComponentfirst then I can't think of other way than to access it via ElementRef and change the attribute manually. This is a very rough solution though. plnkr.co/edit/CfspDAbXHhSi7COsO9Lt?p=preview - AdrianParentComponentfirst? Like an event fromGrandParentComponentthenParentComponentreceives it then finally pass it toChildComponent? - Adrian