5
votes

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
If BeetleJuice's answer is not feasible for you, and if you want to interact directly to the ChildComponent not by passing to the ParentComponent first 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 - Adrian
BTW, can't you do it by going in ParentComponent first? Like an event from GrandParentComponent then ParentComponent receives it then finally pass it to ChildComponent? - Adrian

1 Answers

6
votes

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

  1. 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.

  2. grandparent could write a value to the window object since all components can see it. eg: window.enableControls = false. Child could have a setInterval or Observable.interval that 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.