{ "id": "guide/dependency-injection-navtree", "title": "Navigate the component tree with DI", "contents": "\n\n\n
\n mode_edit\n
\n\n\n
\n

Navigate the component tree with DIlink

\n
\n
Marked for archiving
\n

To ensure that you have the best experience possible, this topic is marked for archiving until we determine\nthat it clearly conveys the most accurate information possible.

\n

In the meantime, this topic might be helpful: Hierarchical injectors.

\n

If you think this content should not be archived, please file a GitHub issue.

\n
\n

Application components often need to share information.\nYou can often use loosely coupled techniques for sharing information,\nsuch as data binding and service sharing,\nbut sometimes it makes sense for one component to have a direct reference to another component.\nYou need a direct reference, for instance, to access values or call methods on that component.

\n

Obtaining a component reference is a bit tricky in Angular.\nAngular components themselves do not have a tree that you can\ninspect or navigate programmatically. The parent-child relationship is indirect,\nestablished through the components' view objects.

\n

Each component has a host view, and can have additional embedded views.\nAn embedded view in component A is the\nhost view of component B, which can in turn have embedded view.\nThis means that there is a view hierarchy for each component,\nof which that component's host view is the root.

\n

There is an API for navigating down the view hierarchy.\nCheck out Query, QueryList, ViewChildren, and ContentChildren\nin the API Reference.

\n

There is no public API for acquiring a parent reference.\nHowever, because every component instance is added to an injector's container,\nyou can use Angular dependency injection to reach a parent component.

\n

This section describes some techniques for doing that.

\n\n\n

Find a parent component of known typelink

\n

You use standard class injection to acquire a parent component whose type you know.

\n

In the following example, the parent AlexComponent has several children including a CathyComponent:

\n\n\n@Component({\n selector: 'alex',\n template: `\n <div class=\"a\">\n <h3>{{name}}</h3>\n <cathy></cathy>\n <craig></craig>\n <carol></carol>\n </div>`,\n})\nexport class AlexComponent extends Base\n{\n name = 'Alex';\n}\n\n\n

Cathy reports whether or not she has access to Alex\nafter injecting an AlexComponent into her constructor:

\n\n@Component({\n selector: 'cathy',\n template: `\n <div class=\"c\">\n <h3>Cathy</h3>\n {{alex ? 'Found' : 'Did not find'}} Alex via the component class.<br>\n </div>`\n})\nexport class CathyComponent {\n constructor( @Optional() public alex?: AlexComponent ) { }\n}\n\n\n

Notice that even though the @Optional qualifier\nis there for safety,\nthe \nconfirms that the alex parameter is set.

\n\n

Unable to find a parent by its base classlink

\n

What if you don't know the concrete parent component class?

\n

A re-usable component might be a child of multiple components.\nImagine a component for rendering breaking news about a financial instrument.\nFor business reasons, this news component makes frequent calls\ndirectly into its parent instrument as changing market data streams by.

\n

The app probably defines more than a dozen financial instrument components.\nIf you're lucky, they all implement the same base class\nwhose API your NewsComponent understands.

\n
\n

Looking for components that implement an interface would be better.\nThat's not possible because TypeScript interfaces disappear\nfrom the transpiled JavaScript, which doesn't support interfaces.\nThere's no artifact to look for.

\n
\n

This isn't necessarily good design.\nThis example is examining whether a component can\ninject its parent via the parent's base class.

\n

The sample's CraigComponent explores this question. Looking back,\nyou see that the Alex component extends (inherits) from a class named Base.

\n\nexport class AlexComponent extends Base\n\n\n

The CraigComponent tries to inject Base into its alex constructor parameter and reports if it succeeded.

\n\n@Component({\n selector: 'craig',\n template: `\n <div class=\"c\">\n <h3>Craig</h3>\n {{alex ? 'Found' : 'Did not find'}} Alex via the base class.\n </div>`\n})\nexport class CraigComponent {\n constructor( @Optional() public alex?: Base ) { }\n}\n\n\n

Unfortunately, this doesn't work.\nThe \nconfirms that the alex parameter is null.\nYou cannot inject a parent by its base class.

\n\n

Find a parent by its class interfacelink

\n

You can find a parent component with a class interface.

\n

The parent must cooperate by providing an alias to itself in the name of a class interface token.

\n

Recall that Angular always adds a component instance to its own injector;\nthat's why you could inject Alex into Cathy earlier.

\n

Write an alias provider—a provide object literal with a useExisting\ndefinition—that creates an alternative way to inject the same component instance\nand add that provider to the providers array of the @Component() metadata for the AlexComponent.

\n\n\nproviders: [{ provide: Parent, useExisting: forwardRef(() => AlexComponent) }],\n\n\n

Parent is the provider's class interface token.\nThe forwardRef breaks the circular reference you just created by having the AlexComponent refer to itself.

\n

Carol, the third of Alex's child components, injects the parent into its parent parameter,\nthe same way you've done it before.

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

Here's Alex and family in action.

\n
\n \"Alex\n
\n\n

Find a parent in a tree with @SkipSelf()link

\n

Imagine one branch of a component hierarchy: Alice -> Barry -> Carol.\nBoth Alice and Barry implement the Parent class interface.

\n

Barry is the problem. He needs to reach his parent, Alice, and also be a parent to Carol.\nThat means he must both inject the Parent class interface to get Alice and\nprovide a Parent to satisfy Carol.

\n

Here's Barry.

\n\nconst templateB = `\n <div class=\"b\">\n <div>\n <h3>{{name}}</h3>\n <p>My parent is {{parent?.name}}</p>\n </div>\n <carol></carol>\n <chris></chris>\n </div>`;\n\n@Component({\n selector: 'barry',\n template: templateB,\n providers: [{ provide: Parent, useExisting: forwardRef(() => BarryComponent) }]\n})\nexport class BarryComponent implements Parent {\n name = 'Barry';\n constructor( @SkipSelf() @Optional() public parent?: Parent ) { }\n}\n\n\n

Barry's providers array looks just like Alex's.\nIf you're going to keep writing alias providers like this you should create a helper function.

\n

For now, focus on Barry's constructor.

\n\n\n \nconstructor( @SkipSelf() @Optional() public parent?: Parent ) { }\n\n\n\n \nconstructor( @Optional() public parent?: Parent ) { }\n\n\n\n\n

It's identical to Carol's constructor except for the additional @SkipSelf decorator.

\n

@SkipSelf is essential for two reasons:

\n
    \n
  1. \n

    It tells the injector to start its search for a Parent dependency in a component above itself,\nwhich is what parent means.

    \n
  2. \n
  3. \n

    Angular throws a cyclic dependency error if you omit the @SkipSelf decorator.

    \n

    NG0200: Circular dependency in DI detected for BethComponent. Dependency path: BethComponent -> Parent -> BethComponent

    \n
  4. \n
\n

Here's Alice, Barry, and family in action.

\n
\n \"Alice\n
\n\n

Parent class interfacelink

\n

You learned earlier that a class interface is an abstract class used as an interface rather than as a base class.

\n

The example defines a Parent class interface.

\n\nexport abstract class Parent { name: string; }\n\n\n

The Parent class interface defines a name property with a type declaration but no implementation.\nThe name property is the only member of a parent component that a child component can call.\nSuch a narrow interface helps decouple the child component class from its parent components.

\n

A component that could serve as a parent should implement the class interface as the AliceComponent does.

\n\nexport class AliceComponent implements Parent\n\n\n

Doing so adds clarity to the code. But it's not technically necessary.\nAlthough AlexComponent has a name property, as required by its Base class,\nits class signature doesn't mention Parent.

\n\nexport class AlexComponent extends Base\n\n\n
\n

AlexComponent should implement Parent as a matter of proper style.\nIt doesn't in this example only to demonstrate that the code will compile and run without the interface.

\n
\n\n \n
\n\n\n" }