angular-cn/aio/dist/generated/docs/guide/dependency-injection-navtree.json

5 lines
18 KiB
JSON

{
"id": "guide/dependency-injection-navtree",
"title": "Navigate the component tree with DI",
"contents": "\n\n\n<div class=\"github-links\">\n <a href=\"https://github.com/angular/angular/edit/master/aio/content/guide/dependency-injection-navtree.md?message=docs%3A%20describe%20your%20change...\" aria-label=\"Suggest Edits\" title=\"Suggest Edits\"><i class=\"material-icons\" aria-hidden=\"true\" role=\"img\">mode_edit</i></a>\n</div>\n\n\n<div class=\"content\">\n <h1 id=\"navigate-the-component-tree-with-di\">Navigate the component tree with DI<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection-navtree#navigate-the-component-tree-with-di\"><i class=\"material-icons\">link</i></a></h1>\n<div class=\"callout is-critical\">\n<header>Marked for archiving</header>\n<p>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.</p>\n<p>In the meantime, this topic might be helpful: <a href=\"guide/hierarchical-dependency-injection\">Hierarchical injectors</a>.</p>\n<p>If you think this content should not be archived, please file a <a href=\"https://github.com/angular/angular/issues/new?template=3-docs-bug.md\">GitHub issue</a>.</p>\n</div>\n<p>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.</p>\n<p>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' <a href=\"guide/glossary#view\">view objects</a>.</p>\n<p>Each component has a <em>host view</em>, and can have additional <em>embedded views</em>.\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 <a href=\"guide/glossary#view-hierarchy\">view hierarchy</a> for each component,\nof which that component's host view is the root.</p>\n<p>There is an API for navigating <em>down</em> the view hierarchy.\nCheck out <code><a href=\"api/core/Query\" class=\"code-anchor\">Query</a></code>, <code><a href=\"api/core/QueryList\" class=\"code-anchor\">QueryList</a></code>, <code><a href=\"api/core/ViewChildren\" class=\"code-anchor\">ViewChildren</a></code>, and <code><a href=\"api/core/ContentChildren\" class=\"code-anchor\">ContentChildren</a></code>\nin the <a href=\"api/\">API Reference</a>.</p>\n<p>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.</p>\n<p>This section describes some techniques for doing that.</p>\n<a id=\"find-parent\"></a>\n<a id=\"known-parent\"></a>\n<h3 id=\"find-a-parent-component-of-known-type\">Find a parent component of known type<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection-navtree#find-a-parent-component-of-known-type\"><i class=\"material-icons\">link</i></a></h3>\n<p>You use standard class injection to acquire a parent component whose type you know.</p>\n<p>In the following example, the parent <code>AlexComponent</code> has several children including a <code>CathyComponent</code>:</p>\n<a id=\"alex\"></a>\n<code-example path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"alex-1\" header=\"parent-finder.component.ts (AlexComponent v.1)\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'alex',\n template: `\n &#x3C;div class=\"a\">\n &#x3C;h3>{{name}}&#x3C;/h3>\n &#x3C;cathy>&#x3C;/cathy>\n &#x3C;craig>&#x3C;/craig>\n &#x3C;carol>&#x3C;/carol>\n &#x3C;/div>`,\n})\nexport class AlexComponent extends Base\n{\n name = 'Alex';\n}\n\n</code-example>\n<p><em>Cathy</em> reports whether or not she has access to <em>Alex</em>\nafter injecting an <code>AlexComponent</code> into her constructor:</p>\n<code-example path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"cathy\" header=\"parent-finder.component.ts (CathyComponent)\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'cathy',\n template: `\n &#x3C;div class=\"c\">\n &#x3C;h3>Cathy&#x3C;/h3>\n {{alex ? 'Found' : 'Did not find'}} Alex via the component class.&#x3C;br>\n &#x3C;/div>`\n})\nexport class CathyComponent {\n constructor( @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>() public alex?: AlexComponent ) { }\n}\n\n</code-example>\n<p>Notice that even though the <a href=\"guide/dependency-injection-in-action#optional\">@Optional</a> qualifier\nis there for safety,\nthe <live-example name=\"dependency-injection-in-action\"></live-example>\nconfirms that the <code>alex</code> parameter is set.</p>\n<a id=\"base-parent\"></a>\n<h3 id=\"unable-to-find-a-parent-by-its-base-class\">Unable to find a parent by its base class<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection-navtree#unable-to-find-a-parent-by-its-base-class\"><i class=\"material-icons\">link</i></a></h3>\n<p>What if you <em>don't</em> know the concrete parent component class?</p>\n<p>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.</p>\n<p>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 <code>NewsComponent</code> understands.</p>\n<div class=\"alert is-helpful\">\n<p>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.</p>\n</div>\n<p>This isn't necessarily good design.\nThis example is examining <em>whether a component can\ninject its parent via the parent's base class</em>.</p>\n<p>The sample's <code>CraigComponent</code> explores this question. <a href=\"guide/dependency-injection-navtree#alex\">Looking back</a>,\nyou see that the <code>Alex</code> component <em>extends</em> (<em>inherits</em>) from a class named <code>Base</code>.</p>\n<code-example path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"alex-class-signature\" header=\"parent-finder.component.ts (Alex class signature)\">\nexport class AlexComponent extends Base\n\n</code-example>\n<p>The <code>CraigComponent</code> tries to inject <code>Base</code> into its <code>alex</code> constructor parameter and reports if it succeeded.</p>\n<code-example path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"craig\" header=\"parent-finder.component.ts (CraigComponent)\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'craig',\n template: `\n &#x3C;div class=\"c\">\n &#x3C;h3>Craig&#x3C;/h3>\n {{alex ? 'Found' : 'Did not find'}} Alex via the base class.\n &#x3C;/div>`\n})\nexport class CraigComponent {\n constructor( @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>() public alex?: Base ) { }\n}\n\n</code-example>\n<p>Unfortunately, this doesn't work.\nThe <live-example name=\"dependency-injection-in-action\"></live-example>\nconfirms that the <code>alex</code> parameter is null.\n<em>You cannot inject a parent by its base class.</em></p>\n<a id=\"class-interface-parent\"></a>\n<h3 id=\"find-a-parent-by-its-class-interface\">Find a parent by its class interface<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection-navtree#find-a-parent-by-its-class-interface\"><i class=\"material-icons\">link</i></a></h3>\n<p>You can find a parent component with a <a href=\"guide/dependency-injection-in-action#class-interface\">class interface</a>.</p>\n<p>The parent must cooperate by providing an <em>alias</em> to itself in the name of a class interface token.</p>\n<p>Recall that Angular always adds a component instance to its own injector;\nthat's why you could inject <em>Alex</em> into <em>Cathy</em> <a href=\"guide/dependency-injection-navtree#known-parent\">earlier</a>.</p>\n<p>Write an <a href=\"guide/dependency-injection-in-action#useexisting\"><em>alias provider</em></a>—a <code>provide</code> object literal with a <code>useExisting</code>\ndefinition—that creates an <em>alternative</em> way to inject the same component instance\nand add that provider to the <code>providers</code> array of the <code>@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>()</code> metadata for the <code>AlexComponent</code>.</p>\n<a id=\"alex-providers\"></a>\n<code-example path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"alex-providers\" header=\"parent-finder.component.ts (AlexComponent providers)\">\nproviders: [{ provide: Parent, useExisting: <a href=\"api/core/forwardRef\" class=\"code-anchor\">forwardRef</a>(() => AlexComponent) }],\n\n</code-example>\n<p><a href=\"guide/dependency-injection-navtree#parent-token\">Parent</a> is the provider's class interface token.\nThe <a href=\"guide/dependency-injection-in-action#forwardref\"><em>forwardRef</em></a> breaks the circular reference you just created by having the <code>AlexComponent</code> refer to itself.</p>\n<p><em>Carol</em>, the third of <em>Alex</em>'s child components, injects the parent into its <code>parent</code> parameter,\nthe same way you've done it before.</p>\n<code-example path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"carol-class\" header=\"parent-finder.component.ts (CarolComponent class)\">\nexport class CarolComponent {\n name = 'Carol';\n constructor( @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>() public parent?: Parent ) { }\n}\n\n</code-example>\n<p>Here's <em>Alex</em> and family in action.</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/dependency-injection-in-action/alex.png\" alt=\"Alex in action\" width=\"302\" height=\"374\">\n</div>\n<a id=\"parent-tree\"></a>\n<h3 id=\"find-a-parent-in-a-tree-with-skipself\">Find a parent in a tree with <em>@SkipSelf()</em><a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection-navtree#find-a-parent-in-a-tree-with-skipself\"><i class=\"material-icons\">link</i></a></h3>\n<p>Imagine one branch of a component hierarchy: <em>Alice</em> -> <em>Barry</em> -> <em>Carol</em>.\nBoth <em>Alice</em> and <em>Barry</em> implement the <code>Parent</code> class interface.</p>\n<p><em>Barry</em> is the problem. He needs to reach his parent, <em>Alice</em>, and also be a parent to <em>Carol</em>.\nThat means he must both <em>inject</em> the <code>Parent</code> class interface to get <em>Alice</em> and\n<em>provide</em> a <code>Parent</code> to satisfy <em>Carol</em>.</p>\n<p>Here's <em>Barry</em>.</p>\n<code-example path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"barry\" header=\"parent-finder.component.ts (BarryComponent)\">\nconst templateB = `\n &#x3C;div class=\"b\">\n &#x3C;div>\n &#x3C;h3>{{name}}&#x3C;/h3>\n &#x3C;p>My parent is {{parent?.name}}&#x3C;/p>\n &#x3C;/div>\n &#x3C;carol>&#x3C;/carol>\n &#x3C;chris>&#x3C;/chris>\n &#x3C;/div>`;\n\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'barry',\n template: templateB,\n providers: [{ provide: Parent, useExisting: <a href=\"api/core/forwardRef\" class=\"code-anchor\">forwardRef</a>(() => BarryComponent) }]\n})\nexport class BarryComponent implements Parent {\n name = 'Barry';\n constructor( @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>() @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>() public parent?: Parent ) { }\n}\n\n</code-example>\n<p><em>Barry</em>'s <code>providers</code> array looks just like <a href=\"guide/dependency-injection-navtree#alex-providers\"><em>Alex</em>'s</a>.\nIf you're going to keep writing <a href=\"guide/dependency-injection-in-action#useexisting\"><em>alias providers</em></a> like this you should create a helper function.</p>\n<p>For now, focus on <em>Barry</em>'s constructor.</p>\n<code-tabs>\n\n <code-pane header=\"Barry&#x27;s constructor\" path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"barry-ctor\">\nconstructor( @<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a>() @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>() public parent?: Parent ) { }\n\n</code-pane>\n\n <code-pane header=\"Carol&#x27;s constructor\" path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"carol-ctor\">\nconstructor( @<a href=\"api/core/Optional\" class=\"code-anchor\">Optional</a>() public parent?: Parent ) { }\n\n</code-pane>\n\n</code-tabs>\n<p>It's identical to <em>Carol</em>'s constructor except for the additional <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a></code> decorator.</p>\n<p><code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a></code> is essential for two reasons:</p>\n<ol>\n<li>\n<p>It tells the injector to start its search for a <code>Parent</code> dependency in a component <em>above</em> itself,\nwhich <em>is</em> what parent means.</p>\n</li>\n<li>\n<p>Angular throws a cyclic dependency error if you omit the <code>@<a href=\"api/core/SkipSelf\" class=\"code-anchor\">SkipSelf</a></code> decorator.</p>\n<p><code>NG0200: Circular dependency in DI detected for BethComponent. Dependency path: BethComponent -> Parent -> BethComponent</code></p>\n</li>\n</ol>\n<p>Here's <em>Alice</em>, <em>Barry</em>, and family in action.</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/dependency-injection-in-action/alice.png\" alt=\"Alice in action\" width=\"298\" height=\"631\">\n</div>\n<a id=\"parent-token\"></a>\n<h3 id=\"parent-class-interface\">Parent class interface<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/dependency-injection-navtree#parent-class-interface\"><i class=\"material-icons\">link</i></a></h3>\n<p>You <a href=\"guide/dependency-injection-in-action#class-interface\">learned earlier</a> that a class interface is an abstract class used as an interface rather than as a base class.</p>\n<p>The example defines a <code>Parent</code> class interface.</p>\n<code-example path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"parent\" header=\"parent-finder.component.ts (Parent class-interface)\">\nexport abstract class Parent { name: string; }\n\n</code-example>\n<p>The <code>Parent</code> class interface defines a <code>name</code> property with a type declaration but <em>no implementation</em>.\nThe <code>name</code> 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.</p>\n<p>A component that could serve as a parent <em>should</em> implement the class interface as the <code>AliceComponent</code> does.</p>\n<code-example path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"alice-class-signature\" header=\"parent-finder.component.ts (AliceComponent class signature)\">\nexport class AliceComponent implements Parent\n\n</code-example>\n<p>Doing so adds clarity to the code. But it's not technically necessary.\nAlthough <code>AlexComponent</code> has a <code>name</code> property, as required by its <code>Base</code> class,\nits class signature doesn't mention <code>Parent</code>.</p>\n<code-example path=\"dependency-injection-in-action/src/app/parent-finder.component.ts\" region=\"alex-class-signature\" header=\"parent-finder.component.ts (AlexComponent class signature)\">\nexport class AlexComponent extends Base\n\n</code-example>\n<div class=\"alert is-helpful\">\n<p><code>AlexComponent</code> <em>should</em> implement <code>Parent</code> as a matter of proper style.\nIt doesn't in this example <em>only</em> to demonstrate that the code will compile and run without the interface.</p>\n</div>\n\n \n</div>\n\n<!-- links to this doc:\n - api/core/TemplateRef\n-->\n<!-- links from this doc:\n - api/\n - api/core/Component\n - api/core/ContentChildren\n - api/core/Optional\n - api/core/Query\n - api/core/QueryList\n - api/core/SkipSelf\n - api/core/ViewChildren\n - api/core/forwardRef\n - guide/dependency-injection-in-action#class-interface\n - guide/dependency-injection-in-action#forwardref\n - guide/dependency-injection-in-action#optional\n - guide/dependency-injection-in-action#useexisting\n - guide/dependency-injection-navtree#alex\n - guide/dependency-injection-navtree#alex-providers\n - guide/dependency-injection-navtree#find-a-parent-by-its-class-interface\n - guide/dependency-injection-navtree#find-a-parent-component-of-known-type\n - guide/dependency-injection-navtree#find-a-parent-in-a-tree-with-skipself\n - guide/dependency-injection-navtree#known-parent\n - guide/dependency-injection-navtree#navigate-the-component-tree-with-di\n - guide/dependency-injection-navtree#parent-class-interface\n - guide/dependency-injection-navtree#parent-token\n - guide/dependency-injection-navtree#unable-to-find-a-parent-by-its-base-class\n - guide/glossary#view\n - guide/glossary#view-hierarchy\n - guide/hierarchical-dependency-injection\n - https://github.com/angular/angular/edit/master/aio/content/guide/dependency-injection-navtree.md?message=docs%3A%20describe%20your%20change...\n - https://github.com/angular/angular/issues/new?template=3-docs-bug.md\n-->"
}