angularparent-childangular14angular-providersangular-dependency-injection

Angular, Unable to find the root parent by its class interface


From the angular documentation here, I had created a Parent class using

export abstract class Parent {}

Inside the AlexComponent, I had provided this component as Parent to its children

providers: [{ provide: Parent, useExisting: forwardRef(() => AlexComponent) }]

Im able to access the parent inside the child component using

export class CarolComponent {
   name = 'Carol';
   constructor( @Optional() public parent?: Parent ) { }
}

But I am unable to access the parent inside the nested child components. That means parent provider gives the immediate Parent but I want to access the root parent.

For example, In this screenshot,

enter image description here

I want the Chris component to access the Alice Component (root parent but not immediate parent)

Is there a way to access the root parent ?


Solution

  • I've created an example in stackblitz and it works. I don't know if it's what you want to do. The child component Chris access root parent Alice injecting the Parent class.

    https://stackblitz.com/edit/angular-accessing-root-parent