Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 - Grandchild Access

Tags:

angular

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?

like image 799
xiotee Avatar asked Oct 20 '16 01:10

xiotee


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

  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.

like image 54
BeetleJuice Avatar answered Oct 08 '22 10:10

BeetleJuice