angular-cn/aio/dist/generated/docs/guide/lifecycle-hooks.json

5 lines
43 KiB
JSON
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

{
"id": "guide/lifecycle-hooks",
"title": "Lifecycle hooks",
"contents": "\n\n\n<div class=\"github-links\">\n <a href=\"https://github.com/angular/angular/edit/master/aio/content/guide/lifecycle-hooks.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=\"lifecycle-hooks\">Lifecycle hooks<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#lifecycle-hooks\"><i class=\"material-icons\">link</i></a></h1>\n<p>A component instance has a lifecycle that starts when Angular instantiates the component class and renders the component view along with its child views.\nThe lifecycle continues with change detection, as Angular checks to see when data-bound properties change, and updates both the view and the component instance as needed.\nThe lifecycle ends when Angular destroys the component instance and removes its rendered template from the DOM.\nDirectives have a similar lifecycle, as Angular creates, updates, and destroys instances in the course of execution.</p>\n<p>Your application can use <a href=\"guide/glossary#lifecycle-hook\" title=\"Definition of lifecycle hook\">lifecycle hook methods</a> to tap into key events in the lifecycle of a component or directive in order to initialize new instances, initiate change detection when needed, respond to updates during change detection, and clean up before deletion of instances.</p>\n<h2 id=\"prerequisites\">Prerequisites<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#prerequisites\"><i class=\"material-icons\">link</i></a></h2>\n<p>Before working with lifecycle hooks, you should have a basic understanding of the following:</p>\n<ul>\n<li><a href=\"https://www.typescriptlang.org/\">TypeScript programming</a>.</li>\n<li>Angular app-design fundamentals, as described in <a href=\"guide/architecture\" title=\"Introduction to fundamental app-design concepts\">Angular Concepts</a>.</li>\n</ul>\n<a id=\"hooks-overview\"></a>\n<h2 id=\"responding-to-lifecycle-events\">Responding to lifecycle events<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#responding-to-lifecycle-events\"><i class=\"material-icons\">link</i></a></h2>\n<p>You can respond to events in the lifecycle of a component or directive by implementing one or more of the <em>lifecycle hook</em> interfaces in the Angular <code>core</code> library.\nThe hooks give you the opportunity to act on a component or directive instance at the appropriate moment, as Angular creates, updates, or destroys that instance.</p>\n<p>Each interface defines the prototype for a single hook method, whose name is the interface name prefixed with <code>ng</code>.\nFor example, the <code><a href=\"api/core/OnInit\" class=\"code-anchor\">OnInit</a></code> interface has a hook method named <code>ngOnInit()</code>. If you implement this method in your component or directive class, Angular calls it shortly after checking the input properties for that component or directive for the first time.</p>\n<code-example path=\"lifecycle-hooks/src/app/peek-a-boo.directive.ts\" region=\"ngOnInit\" header=\"peek-a-boo.directive.ts (excerpt)\">\n@<a href=\"api/core/Directive\" class=\"code-anchor\">Directive</a>()\nexport class PeekABooDirective implements <a href=\"api/core/OnInit\" class=\"code-anchor\">OnInit</a> {\n constructor(private logger: LoggerService) { }\n\n // implement <a href=\"api/core/OnInit\" class=\"code-anchor\">OnInit</a>'s `ngOnInit` method\n ngOnInit() {\n this.logIt(`<a href=\"api/core/OnInit\" class=\"code-anchor\">OnInit</a>`);\n }\n\n logIt(msg: string) {\n this.logger.log(`#${nextId++} ${msg}`);\n }\n}\n\n</code-example>\n<p>You don't have to implement all (or any) of the lifecycle hooks, just the ones you need.</p>\n<a id=\"hooks-purpose-timing\"></a>\n<h3 id=\"lifecycle-event-sequence\">Lifecycle event sequence<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#lifecycle-event-sequence\"><i class=\"material-icons\">link</i></a></h3>\n<p>After your application instantiates a component or directive by calling its constructor, Angular calls the hook methods you have implemented at the appropriate point in the lifecycle of that instance.</p>\n<p>Angular executes hook methods in the following sequence. You can use them to perform the following kinds of operations.</p>\n<table width=\"100%\">\n <colgroup><col width=\"20%\">\n <col width=\"60%\">\n <col width=\"20%\">\n </colgroup><tbody><tr>\n <th>Hook method</th>\n <th>Purpose</th>\n <th>Timing</th>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <code>ngOnChanges()</code>\n </td>\n <td>\n<p> Respond when Angular sets or resets data-bound input properties.\nThe method receives a <code><a href=\"api/core/SimpleChanges\" class=\"code-anchor\">SimpleChanges</a></code> object of current and previous property values.</p>\n<p> Note that this happens very frequently, so any operation you perform here impacts performance significantly.\nSee details in <a href=\"guide/lifecycle-hooks#onchanges\">Using change detection hooks</a> in this document.</p>\n </td>\n <td>\n<p> Called before <code>ngOnInit()</code> and whenever one or more data-bound input properties change.</p>\n<p> Note that if your component has no inputs or you use it without providing any inputs, the framework will not call <code>ngOnChanges()</code>.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <code>ngOnInit()</code>\n </td>\n <td>\n<p> Initialize the directive or component after Angular first displays the data-bound properties\nand sets the directive or component's input properties.\nSee details in <a href=\"guide/lifecycle-hooks#oninit\">Initializing a component or directive</a> in this document.</p>\n </td>\n <td>\n<p> Called once, after the first <code>ngOnChanges()</code>.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <code>ngDoCheck()</code>\n </td>\n <td>\n<p> Detect and act upon changes that Angular can't or won't detect on its own.\nSee details and example in <a href=\"guide/lifecycle-hooks#docheck\">Defining custom change detection</a> in this document.</p>\n </td>\n <td>\n<p> Called immediately after <code>ngOnChanges()</code> on every change detection run, and immediately after <code>ngOnInit()</code> on the first run.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <code>ngAfterContentInit()</code>\n </td>\n <td>\n<p> Respond after Angular projects external content into the component's view, or into the view that a directive is in.</p>\n<p> See details and example in <a href=\"guide/lifecycle-hooks#aftercontent\">Responding to changes in content</a> in this document.</p>\n </td>\n <td>\n<p> Called <em>once</em> after the first <code>ngDoCheck()</code>.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <code>ngAfterContentChecked()</code>\n </td>\n <td>\n<p> Respond after Angular checks the content projected into the directive or component.</p>\n<p> See details and example in <a href=\"guide/lifecycle-hooks#aftercontent\">Responding to projected content changes</a> in this document.</p>\n </td>\n <td>\n<p> Called after <code>ngAfterContentInit()</code> and every subsequent <code>ngDoCheck()</code>.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <code>ngAfterViewInit()</code>\n </td>\n <td>\n<p> Respond after Angular initializes the component's views and child views, or the view that contains the directive.</p>\n<p> See details and example in <a href=\"guide/lifecycle-hooks#afterview\">Responding to view changes</a> in this document.</p>\n </td>\n <td>\n<p> Called <em>once</em> after the first <code>ngAfterContentChecked()</code>.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <code>ngAfterViewChecked()</code>\n </td>\n <td>\n<p> Respond after Angular checks the component's views and child views, or the view that contains the directive.</p>\n </td>\n <td>\n<p> Called after the <code>ngAfterViewInit()</code> and every subsequent <code>ngAfterContentChecked()</code>.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <code>ngOnDestroy()</code>\n </td>\n <td>\n<p> Cleanup just before Angular destroys the directive or component.\nUnsubscribe Observables and detach event handlers to avoid memory leaks.\nSee details in <a href=\"guide/lifecycle-hooks#ondestroy\">Cleaning up on instance destruction</a> in this document.</p>\n </td>\n <td>\n<p> Called immediately before Angular destroys the directive or component.</p>\n </td>\n </tr>\n</tbody></table>\n<a id=\"the-sample\"></a>\n<h3 id=\"lifecycle-example-set\">Lifecycle example set<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#lifecycle-example-set\"><i class=\"material-icons\">link</i></a></h3>\n<p>The <live-example></live-example>\ndemonstrates the use of lifecycle hooks through a series of exercises\npresented as components under the control of the root <code>AppComponent</code>.\nIn each case a <em>parent</em> component serves as a test rig for\na <em>child</em> component that illustrates one or more of the lifecycle hook methods.</p>\n<p>The following table lists the exercises with brief descriptions.\nThe sample code is also used to illustrate specific tasks in the following sections.</p>\n<table width=\"100%\">\n <colgroup><col width=\"20%\">\n <col width=\"80%\">\n </colgroup><tbody><tr>\n <th>Component</th>\n <th>Description</th>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <a href=\"guide/lifecycle-hooks#peek-a-boo\">Peek-a-boo</a>\n </td>\n <td>\n<p> Demonstrates every lifecycle hook.\nEach hook method writes to the on-screen log.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <a href=\"guide/lifecycle-hooks#spy\">Spy</a>\n </td>\n <td>\n<p> Shows how you can use lifecycle hooks with a custom directive.\nThe <code>SpyDirective</code> implements the <code>ngOnInit()</code> and <code>ngOnDestroy()</code> hooks,\nand uses them to watch and report when an element goes in or out of the current view.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <a href=\"guide/lifecycle-hooks#onchanges\">OnChanges</a>\n </td>\n <td>\n<p> Demonstrates how Angular calls the <code>ngOnChanges()</code> hook\nevery time one of the component input properties changes,\nand shows how to interpret the <code>changes</code> object passed to the hook method.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <a href=\"guide/lifecycle-hooks#docheck\">DoCheck</a>\n </td>\n <td>\n<p> Implements the <code>ngDoCheck()</code> method with custom change detection.\nWatch the hook post changes to a log to see how often Angular calls this hook.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <a href=\"guide/lifecycle-hooks#afterview\">AfterView</a>\n </td>\n <td>\n<p> Shows what Angular means by a <a href=\"guide/glossary#view\" title=\"Definition of view.\">view</a>.\nDemonstrates the <code>ngAfterViewInit()</code> and <code>ngAfterViewChecked()</code> hooks.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <a href=\"guide/lifecycle-hooks#aftercontent\">AfterContent</a>\n </td>\n <td>\n<p> Shows how to project external content into a component and\nhow to distinguish projected content from a component's view children.\nDemonstrates the <code>ngAfterContentInit()</code> and <code>ngAfterContentChecked()</code> hooks.</p>\n </td>\n </tr>\n <tr style=\"vertical-align:top\">\n <td>\n <a href=\"guide/lifecycle-hooks#counter\">Counter</a>\n </td>\n <td>\n<p> Demonstrates a combination of a component and a directive, each with its own hooks.</p>\n </td>\n </tr>\n</tbody></table>\n<a id=\"oninit\"></a>\n<h2 id=\"initializing-a-component-or-directive\">Initializing a component or directive<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#initializing-a-component-or-directive\"><i class=\"material-icons\">link</i></a></h2>\n<p>Use the <code>ngOnInit()</code> method to perform the following initialization tasks.</p>\n<ul>\n<li>\n<p>Perform complex initializations outside of the constructor.\nComponents should be cheap and safe to construct.\nYou should not, for example, fetch data in a component constructor.\nYou shouldn't worry that a new component will try to contact a remote server when\ncreated under test or before you decide to display it.</p>\n<p>An <code>ngOnInit()</code> is a good place for a component to fetch its initial data.\nFor an example, see the <a href=\"tutorial/toh-pt4#oninit\">Tour of Heroes tutorial</a>.</p>\n</li>\n</ul>\n<ul>\n<li>\n<p>Set up the component after Angular sets the input properties.\nConstructors should do no more than set the initial local variables to simple values.</p>\n<p>Keep in mind that a directive's data-bound input properties are not set until <em>after construction</em>.\nIf you need to initialize the directive based on those properties, set them when <code>ngOnInit()</code> runs.</p>\n<div class=\"alert is-helpful\">\n<p> The <code>ngOnChanges()</code> method is your first opportunity to access those properties.\nAngular calls <code>ngOnChanges()</code> before <code>ngOnInit()</code>, but also many times after that.\nIt only calls <code>ngOnInit()</code> once.</p>\n</div>\n</li>\n</ul>\n<a id=\"ondestroy\"></a>\n<h2 id=\"cleaning-up-on-instance-destruction\">Cleaning up on instance destruction<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#cleaning-up-on-instance-destruction\"><i class=\"material-icons\">link</i></a></h2>\n<p>Put cleanup logic in <code>ngOnDestroy()</code>, the logic that must run before Angular destroys the directive.</p>\n<p>This is the place to free resources that won't be garbage-collected automatically.\nYou risk memory leaks if you neglect to do so.</p>\n<ul>\n<li>Unsubscribe from Observables and DOM events.</li>\n<li>Stop interval timers.</li>\n<li>Unregister all callbacks that the directive registered with global or application services.</li>\n</ul>\n<p>The <code>ngOnDestroy()</code> method is also the time to notify another part of the application that the component is going away.</p>\n<h2 id=\"general-examples\">General examples<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#general-examples\"><i class=\"material-icons\">link</i></a></h2>\n<p>The following examples demonstrate the call sequence and relative frequency of the various lifecycle events, and how the hooks can be used separately or together for components and directives.</p>\n<a id=\"peek-a-boo\"></a>\n<h3 id=\"sequence-and-frequency-of-all-lifecycle-events\">Sequence and frequency of all lifecycle events<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#sequence-and-frequency-of-all-lifecycle-events\"><i class=\"material-icons\">link</i></a></h3>\n<p>To show how Angular calls the hooks in the expected order, the <code>PeekABooComponent</code> demonstrates all of the hooks in one component.</p>\n<p>In practice you would rarely, if ever, implement all of the interfaces the way this demo does.</p>\n<p>The following snapshot reflects the state of the log after the user clicked the <em>Create...</em> button and then the <em>Destroy...</em> button.</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/lifecycle-hooks/peek-a-boo.png\" alt=\"Peek-a-boo\" width=\"309\" height=\"366\">\n</div>\n<p>The sequence of log messages follows the prescribed hook calling order:\n<code><a href=\"api/core/OnChanges\" class=\"code-anchor\">OnChanges</a></code>, <code><a href=\"api/core/OnInit\" class=\"code-anchor\">OnInit</a></code>, <code><a href=\"api/core/DoCheck\" class=\"code-anchor\">DoCheck</a></code> (3x), <code><a href=\"api/core/AfterContentInit\" class=\"code-anchor\">AfterContentInit</a></code>, <code><a href=\"api/core/AfterContentChecked\" class=\"code-anchor\">AfterContentChecked</a></code> (3x),\n<code><a href=\"api/core/AfterViewInit\" class=\"code-anchor\">AfterViewInit</a></code>, <code><a href=\"api/core/AfterViewChecked\" class=\"code-anchor\">AfterViewChecked</a></code> (3x), and <code><a href=\"api/core/OnDestroy\" class=\"code-anchor\">OnDestroy</a></code>.</p>\n<div class=\"alert is-helpful\">\n<p> Notice that the log confirms that input properties (the <code>name</code> property in this case) have no assigned values at construction.\nThe input properties are available to the <code>onInit()</code> method for further initialization.</p>\n</div>\n<p>Had the user clicked the <em>Update Hero</em> button, the log would show another <code><a href=\"api/core/OnChanges\" class=\"code-anchor\">OnChanges</a></code> and two more triplets of <code><a href=\"api/core/DoCheck\" class=\"code-anchor\">DoCheck</a></code>, <code><a href=\"api/core/AfterContentChecked\" class=\"code-anchor\">AfterContentChecked</a></code> and <code><a href=\"api/core/AfterViewChecked\" class=\"code-anchor\">AfterViewChecked</a></code>.\nNotice that these three hooks fire <em>often</em>, so it is important to keep their logic as lean as possible.</p>\n<a id=\"spy\"></a>\n<h3 id=\"use-directives-to-watch-the-dom\">Use directives to watch the DOM<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#use-directives-to-watch-the-dom\"><i class=\"material-icons\">link</i></a></h3>\n<p>The <code>Spy</code> example demonstrates how you can use hook method for directives as well as components.\nThe <code>SpyDirective</code> implements two hooks, <code>ngOnInit()</code> and <code>ngOnDestroy()</code>, in order to discover when a watched element is in the current view.</p>\n<p>This template applies the <code>SpyDirective</code> to a <code>&#x3C;div></code> in the <code><a href=\"api/common/NgForOf\" class=\"code-anchor\">ngFor</a></code> <em>hero</em> repeater managed by the parent <code>SpyComponent</code>.</p>\n<p>The example does not perform any initialization or clean-up.\nIt just tracks the appearance and disappearance of an element in the view by recording when the directive itself is instantiated and destroyed.</p>\n<p>A spy directive like this can provide insight into a DOM object that you cannot change directly.\nYou can't touch the implementation of a native <code>&#x3C;div></code>, or modify a third party component.\nYou can, however watch these elements with a directive.</p>\n<p>The directive defines <code>ngOnInit()</code> and <code>ngOnDestroy()</code> hooks\nthat log messages to the parent via an injected <code>LoggerService</code>.</p>\n<code-example path=\"lifecycle-hooks/src/app/spy.directive.ts\" region=\"spy-directive\" header=\"src/app/spy.directive.ts\">\nlet nextId = 1;\n\n// Spy on any element to which it is applied.\n// Usage: &#x3C;div appSpy>...&#x3C;/div>\n@<a href=\"api/core/Directive\" class=\"code-anchor\">Directive</a>({selector: '[appSpy]'})\nexport class SpyDirective implements <a href=\"api/core/OnInit\" class=\"code-anchor\">OnInit</a>, <a href=\"api/core/OnDestroy\" class=\"code-anchor\">OnDestroy</a> {\n private id = nextId++;\n\n constructor(private logger: LoggerService) { }\n\n ngOnInit() {\n this.logger.log(`Spy #${this.id} onInit`);\n }\n\n ngOnDestroy() {\n this.logger.log(`Spy #${this.id} onDestroy`);\n }\n}\n\n</code-example>\n<p>You can apply the spy to any native or component element, and see that it is initialized and destroyed\nat the same time as that element.\nHere it is attached to the repeated hero <code>&#x3C;div></code>:</p>\n<code-example path=\"lifecycle-hooks/src/app/spy.component.html\" region=\"template\" header=\"src/app/spy.component.html\">\n&#x3C;div *<a href=\"api/common/NgForOf\" class=\"code-anchor\">ngFor</a>=\"let hero of heroes\" appSpy class=\"heroes\">\n {{hero}}\n&#x3C;/div>\n\n</code-example>\n<p>Each spy's creation and destruction marks the appearance and disappearance of the attached hero <code>&#x3C;div></code>\nwith an entry in the <em>Hook Log</em> as seen here:</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/lifecycle-hooks/spy-directive.gif\" alt=\"Spy Directive\" width=\"656\" height=\"378\">\n</div>\n<p>Adding a hero results in a new hero <code>&#x3C;div></code>. The spy's <code>ngOnInit()</code> logs that event.</p>\n<p>The <em>Reset</em> button clears the <code>heroes</code> list.\nAngular removes all hero <code>&#x3C;div></code> elements from the DOM and destroys their spy directives at the same time.\nThe spy's <code>ngOnDestroy()</code> method reports its last moments.</p>\n<a id=\"counter\"></a>\n<h3 id=\"use-component-and-directive-hooks-together\">Use component and directive hooks together<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#use-component-and-directive-hooks-together\"><i class=\"material-icons\">link</i></a></h3>\n<p>In this example, a <code>CounterComponent</code> uses the <code>ngOnChanges()</code> method to log a change every time the parent component increments its input <code>counter</code> property.</p>\n<p>This example applies the <code>SpyDirective</code> from the previous example to the <code>CounterComponent</code> log, in order to watch the creation and destruction of log entries.</p>\n<a id=\"onchanges\"></a>\n<h2 id=\"using-change-detection-hooks\">Using change detection hooks<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#using-change-detection-hooks\"><i class=\"material-icons\">link</i></a></h2>\n<p>Angular calls the <code>ngOnChanges()</code> method of a component or directive whenever it detects changes to the <strong><em>input properties</em></strong>.\nThe <em>onChanges</em> example demonstrates this by monitoring the <code><a href=\"api/core/OnChanges\" class=\"code-anchor\">OnChanges</a>()</code> hook.</p>\n<code-example path=\"lifecycle-hooks/src/app/on-changes.component.ts\" region=\"ng-on-changes\" header=\"on-changes.component.ts (excerpt)\">\nngOnChanges(changes: <a href=\"api/core/SimpleChanges\" class=\"code-anchor\">SimpleChanges</a>) {\n for (const propName in changes) {\n const chng = changes[propName];\n const cur = JSON.stringify(chng.currentValue);\n const prev = JSON.stringify(chng.previousValue);\n this.changeLog.push(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);\n }\n}\n\n</code-example>\n<p>The <code>ngOnChanges()</code> method takes an object that maps each changed property name to a\n<a href=\"api/core/SimpleChange\">SimpleChange</a> object holding the current and previous property values.\nThis hook iterates over the changed properties and logs them.</p>\n<p>The example component, <code>OnChangesComponent</code>, has two input properties: <code>hero</code> and <code>power</code>.</p>\n<code-example path=\"lifecycle-hooks/src/app/on-changes.component.ts\" region=\"inputs\" header=\"src/app/on-changes.component.ts\">\n@<a href=\"api/core/Input\" class=\"code-anchor\">Input</a>() hero: Hero;\n@<a href=\"api/core/Input\" class=\"code-anchor\">Input</a>() power: string;\n\n</code-example>\n<p>The host <code>OnChangesParentComponent</code> binds to them as follows.</p>\n<code-example path=\"lifecycle-hooks/src/app/on-changes-parent.component.html\" region=\"on-changes\" header=\"src/app/on-changes-parent.component.html\">\n&#x3C;on-changes [hero]=\"hero\" [power]=\"power\">&#x3C;/on-changes>\n\n</code-example>\n<p>Here's the sample in action as the user makes changes.</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/lifecycle-hooks/on-changes-anim.gif\" alt=\"OnChanges\" width=\"632\" height=\"512\">\n</div>\n<p>The log entries appear as the string value of the <em>power</em> property changes.\nNotice, however, that the <code>ngOnChanges()</code> method does not catch changes to <code>hero.name</code>.\nThis is because Angular calls the hook only when the value of the input property changes.\nIn this case, <code>hero</code> is the input property, and the value of the <code>hero</code> property is the <em>reference to the hero object</em>.\nThe object reference did not change when the value of its own <code>name</code> property changed.</p>\n<a id=\"afterview\"></a>\n<h3 id=\"responding-to-view-changes\">Responding to view changes<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#responding-to-view-changes\"><i class=\"material-icons\">link</i></a></h3>\n<p>As Angular traverses the <a href=\"guide/glossary#view-hierarchy\" title=\"Definition of view hierarchy definition\">view hierarchy</a> during change detection, it needs to be sure that a change in a child does not attempt to cause a change in its own parent. Such a change would not be rendered properly, because of how <a href=\"guide/glossary#unidirectional-data-flow\" title=\"Definition\">unidirectional data flow</a> works.</p>\n<p>If you need to make a change that inverts the expected data flow, you must trigger a new change detection cycle to allow that change to be rendered.\nThe examples illustrate how to make such changes safely.</p>\n<p>The <em>AfterView</em> sample explores the <code><a href=\"api/core/AfterViewInit\" class=\"code-anchor\">AfterViewInit</a>()</code> and <code><a href=\"api/core/AfterViewChecked\" class=\"code-anchor\">AfterViewChecked</a>()</code> hooks that Angular calls\n<em>after</em> it creates a component's child views.</p>\n<p>Here's a child view that displays a hero's name in an <code>&#x3C;input></code>:</p>\n<code-example path=\"lifecycle-hooks/src/app/child-view.component.ts\" region=\"child-view\" header=\"ChildViewComponent\">\n@<a href=\"api/core/Component\" class=\"code-anchor\">Component</a>({\n selector: 'app-child-view',\n template: '&#x3C;input [(<a href=\"api/forms/NgModel\" class=\"code-anchor\">ngModel</a>)]=\"hero\">'\n})\nexport class ChildViewComponent {\n hero = 'Magneta';\n}\n\n</code-example>\n<p>The <code>AfterViewComponent</code> displays this child view <em>within its template</em>:</p>\n<code-example path=\"lifecycle-hooks/src/app/after-view.component.ts\" region=\"template\" header=\"AfterViewComponent (template)\">\ntemplate: `\n &#x3C;div>-- child view begins --&#x3C;/div>\n &#x3C;app-child-view>&#x3C;/app-child-view>\n &#x3C;div>-- child view ends --&#x3C;/div>`\n\n</code-example>\n<p>The following hooks take action based on changing values <em>within the child view</em>,\nwhich can only be reached by querying for the child view via the property decorated with\n<a href=\"api/core/ViewChild\">@ViewChild</a>.</p>\n<code-example path=\"lifecycle-hooks/src/app/after-view.component.ts\" region=\"hooks\" header=\"AfterViewComponent (class excerpts)\">\nexport class AfterViewComponent implements <a href=\"api/core/AfterViewChecked\" class=\"code-anchor\">AfterViewChecked</a>, <a href=\"api/core/AfterViewInit\" class=\"code-anchor\">AfterViewInit</a> {\n private prevHero = '';\n\n // <a href=\"api/core/Query\" class=\"code-anchor\">Query</a> for a VIEW child of type `ChildViewComponent`\n @<a href=\"api/core/ViewChild\" class=\"code-anchor\">ViewChild</a>(ChildViewComponent) viewChild: ChildViewComponent;\n\n ngAfterViewInit() {\n // viewChild is set after the view has been initialized\n this.logIt('<a href=\"api/core/AfterViewInit\" class=\"code-anchor\">AfterViewInit</a>');\n this.doSomething();\n }\n\n ngAfterViewChecked() {\n // viewChild is updated after the view has been checked\n if (this.prevHero === this.viewChild.hero) {\n this.logIt('<a href=\"api/core/AfterViewChecked\" class=\"code-anchor\">AfterViewChecked</a> (no change)');\n } else {\n this.prevHero = this.viewChild.hero;\n this.logIt('<a href=\"api/core/AfterViewChecked\" class=\"code-anchor\">AfterViewChecked</a>');\n this.doSomething();\n }\n }\n // ...\n}\n\n</code-example>\n<a id=\"wait-a-tick\"></a>\n<h4 id=\"wait-before-updating-the-view\">Wait before updating the view<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#wait-before-updating-the-view\"><i class=\"material-icons\">link</i></a></h4>\n<p>In this example, the <code>doSomething()</code> method updates the screen when the hero name exceeds 10 characters, but waits a tick before updating <code>comment</code>.</p>\n<code-example path=\"lifecycle-hooks/src/app/after-view.component.ts\" region=\"do-something\" header=\"AfterViewComponent (doSomething)\">\n// This surrogate for real business logic sets the `comment`\nprivate doSomething() {\n const c = this.viewChild.hero.length > 10 ? `That's a long name` : '';\n if (c !== this.comment) {\n // Wait a <a href=\"api/core/testing/tick\" class=\"code-anchor\">tick</a> because the component's view has already been checked\n this.logger.tick_then(() => this.comment = c);\n }\n}\n\n</code-example>\n<p>Both the <code><a href=\"api/core/AfterViewInit\" class=\"code-anchor\">AfterViewInit</a>()</code> and <code><a href=\"api/core/AfterViewChecked\" class=\"code-anchor\">AfterViewChecked</a>()</code> hooks fire after the component's view has been composed.\nIf you modify the code so that the hook updates the component's data-bound <code>comment</code> property immediately, you can see that Angular throws an error.</p>\n<p>The <code>LoggerService.tick_then()</code> statement postpones the log update\nfor one turn of the browser's JavaScript cycle, which triggers a new change-detection cycle.</p>\n<h4 id=\"write-lean-hook-methods-to-avoid-performance-problems\">Write lean hook methods to avoid performance problems<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#write-lean-hook-methods-to-avoid-performance-problems\"><i class=\"material-icons\">link</i></a></h4>\n<p>When you run the <em>AfterView</em> sample, notice how frequently Angular calls <code><a href=\"api/core/AfterViewChecked\" class=\"code-anchor\">AfterViewChecked</a>()</code>-often when there are no changes of interest.\nBe very careful about how much logic or computation you put into one of these methods.</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/lifecycle-hooks/after-view-anim.gif\" alt=\"AfterView\" width=\"520\" height=\"532\">\n</div>\n<a id=\"aftercontent\"></a>\n<a id=\"aftercontent-hooks\"></a>\n<a id=\"content-projection\"></a>\n<h3 id=\"responding-to-projected-content-changes\">Responding to projected content changes<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#responding-to-projected-content-changes\"><i class=\"material-icons\">link</i></a></h3>\n<p><em>Content projection</em> is a way to import HTML content from outside the component and insert that content\ninto the component's template in a designated spot.\nYou can identify content projection in a template by looking for the following constructs.</p>\n<ul>\n<li>HTML between component element tags.</li>\n<li>The presence of <code>&#x3C;ng-content></code> tags in the component's template.</li>\n</ul>\n<div class=\"alert is-helpful\">\n<p> AngularJS developers know this technique as <em>transclusion</em>.</p>\n</div>\n<p>The <em>AfterContent</em> sample explores the <code><a href=\"api/core/AfterContentInit\" class=\"code-anchor\">AfterContentInit</a>()</code> and <code><a href=\"api/core/AfterContentChecked\" class=\"code-anchor\">AfterContentChecked</a>()</code> hooks that Angular calls <em>after</em> Angular projects external content into the component.</p>\n<p>Consider this variation on the <a href=\"guide/lifecycle-hooks#afterview\">previous <em>AfterView</em></a> example.\nThis time, instead of including the child view within the template, it imports the content from\nthe <code>AfterContentComponent</code>'s parent.\nThe following is the parent's template.</p>\n<code-example path=\"lifecycle-hooks/src/app/after-content-parent.component.ts\" region=\"parent-template\" header=\"AfterContentParentComponent (template excerpt)\">\n`&#x3C;after-content>\n &#x3C;app-child>&#x3C;/app-child>\n&#x3C;/after-content>`\n\n</code-example>\n<p>Notice that the <code>&#x3C;app-child></code> tag is tucked between the <code>&#x3C;after-content></code> tags.\nNever put content between a component's element tags <em>unless you intend to project that content\ninto the component</em>.</p>\n<p>Now look at the component's template.</p>\n<code-example path=\"lifecycle-hooks/src/app/after-content.component.ts\" region=\"template\" header=\"AfterContentComponent (template)\">\ntemplate: `\n &#x3C;div>-- projected content begins --&#x3C;/div>\n &#x3C;ng-content>&#x3C;/ng-content>\n &#x3C;div>-- projected content ends --&#x3C;/div>`\n\n</code-example>\n<p>The <code>&#x3C;ng-content></code> tag is a <em>placeholder</em> for the external content.\nIt tells Angular where to insert that content.\nIn this case, the projected content is the <code>&#x3C;app-child></code> from the parent.</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/lifecycle-hooks/projected-child-view.png\" alt=\"Projected Content\" width=\"230\" height=\"89\">\n</div>\n<h4 id=\"using-aftercontent-hooks\">Using AfterContent hooks<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#using-aftercontent-hooks\"><i class=\"material-icons\">link</i></a></h4>\n<p><em>AfterContent</em> hooks are similar to the <em>AfterView</em> hooks.\nThe key difference is in the child component.</p>\n<ul>\n<li>\n<p>The <em>AfterView</em> hooks concern <code><a href=\"api/core/ViewChildren\" class=\"code-anchor\">ViewChildren</a></code>, the child components whose element tags\nappear <em>within</em> the component's template.</p>\n</li>\n<li>\n<p>The <em>AfterContent</em> hooks concern <code><a href=\"api/core/ContentChildren\" class=\"code-anchor\">ContentChildren</a></code>, the child components that Angular\nprojected into the component.</p>\n</li>\n</ul>\n<p>The following <em>AfterContent</em> hooks take action based on changing values in a <em>content child</em>,\nwhich can only be reached by querying for them via the property decorated with\n<a href=\"api/core/ContentChild\">@ContentChild</a>.</p>\n<code-example path=\"lifecycle-hooks/src/app/after-content.component.ts\" region=\"hooks\" header=\"AfterContentComponent (class excerpts)\">\nexport class AfterContentComponent implements <a href=\"api/core/AfterContentChecked\" class=\"code-anchor\">AfterContentChecked</a>, <a href=\"api/core/AfterContentInit\" class=\"code-anchor\">AfterContentInit</a> {\n private prevHero = '';\n comment = '';\n\n // <a href=\"api/core/Query\" class=\"code-anchor\">Query</a> for a CONTENT child of type `ChildComponent`\n @<a href=\"api/core/ContentChild\" class=\"code-anchor\">ContentChild</a>(ChildComponent) contentChild: ChildComponent;\n\n ngAfterContentInit() {\n // contentChild is set after the content has been initialized\n this.logIt('<a href=\"api/core/AfterContentInit\" class=\"code-anchor\">AfterContentInit</a>');\n this.doSomething();\n }\n\n ngAfterContentChecked() {\n // contentChild is updated after the content has been checked\n if (this.prevHero === this.contentChild.hero) {\n this.logIt('<a href=\"api/core/AfterContentChecked\" class=\"code-anchor\">AfterContentChecked</a> (no change)');\n } else {\n this.prevHero = this.contentChild.hero;\n this.logIt('<a href=\"api/core/AfterContentChecked\" class=\"code-anchor\">AfterContentChecked</a>');\n this.doSomething();\n }\n }\n // ...\n}\n\n</code-example>\n<a id=\"no-unidirectional-flow-worries\"></a>\n<div class=\"alert is-helpful\">\n<header>No need to wait for content updates</header>\n<p>This component's <code>doSomething()</code> method updates the component's data-bound <code>comment</code> property immediately.\nThere's no need to <a href=\"guide/lifecycle-hooks#wait-a-tick\" title=\"Delaying updates\">delay the update to ensure proper rendering</a>.</p>\n<p>Angular calls both <em>AfterContent</em> hooks before calling either of the <em>AfterView</em> hooks.\nAngular completes composition of the projected content <em>before</em> finishing the composition of this component's view.\nThere is a small window between the <code>AfterContent...</code> and <code>AfterView...</code> hooks that allows you to modify the host view.</p>\n</div>\n<a id=\"docheck\"></a>\n<h2 id=\"defining-custom-change-detection\">Defining custom change detection<a title=\"Link to this heading\" class=\"header-link\" aria-hidden=\"true\" href=\"guide/lifecycle-hooks#defining-custom-change-detection\"><i class=\"material-icons\">link</i></a></h2>\n<p>To monitor changes that occur where <code>ngOnChanges()</code> won't catch them, you can implement your own change check, as shown in the <em>DoCheck</em> example.\nThis example shows how you can use the <code>ngDoCheck()</code> hook to detect and act upon changes that Angular doesn't catch on its own.</p>\n<p>The <em>DoCheck</em> sample extends the <em>OnChanges</em> sample with the following <code>ngDoCheck()</code> hook:</p>\n<code-example path=\"lifecycle-hooks/src/app/do-check.component.ts\" region=\"ng-do-check\" header=\"DoCheckComponent (ngDoCheck)\">\nngDoCheck() {\n\n if (this.hero.name !== this.oldHeroName) {\n this.changeDetected = true;\n this.changeLog.push(`<a href=\"api/core/DoCheck\" class=\"code-anchor\">DoCheck</a>: Hero name changed to \"${this.hero.name}\" from \"${this.oldHeroName}\"`);\n this.oldHeroName = this.hero.name;\n }\n\n if (this.power !== this.oldPower) {\n this.changeDetected = true;\n this.changeLog.push(`<a href=\"api/core/DoCheck\" class=\"code-anchor\">DoCheck</a>: Power changed to \"${this.power}\" from \"${this.oldPower}\"`);\n this.oldPower = this.power;\n }\n\n if (this.changeDetected) {\n this.noChangeCount = 0;\n } else {\n // log that hook was called when there was no relevant change.\n const count = this.noChangeCount += 1;\n const noChangeMsg = `<a href=\"api/core/DoCheck\" class=\"code-anchor\">DoCheck</a> called ${count}x when no change to hero or power`;\n if (count === 1) {\n // add new \"no change\" message\n this.changeLog.push(noChangeMsg);\n } else {\n // update last \"no change\" message\n this.changeLog[this.changeLog.length - 1] = noChangeMsg;\n }\n }\n\n this.changeDetected = false;\n}\n\n</code-example>\n<p>This code inspects certain <em>values of interest</em>, capturing and comparing their current state against previous values.\nIt writes a special message to the log when there are no substantive changes to the <code>hero</code> or the <code>power</code> so you can see how often <code><a href=\"api/core/DoCheck\" class=\"code-anchor\">DoCheck</a>()</code> is called.\nThe results are illuminating.</p>\n<div class=\"lightbox\">\n <img src=\"generated/images/guide/lifecycle-hooks/do-check-anim.gif\" alt=\"DoCheck\" width=\"632\" height=\"588\">\n</div>\n<p>While the <code>ngDoCheck()</code> hook can detect when the hero's <code>name</code> has changed, it is very expensive.\nThis hook is called with enormous frequency—after <em>every</em>\nchange detection cycle no matter where the change occurred.\nIt's called over twenty times in this example before the user can do anything.</p>\n<p>Most of these initial checks are triggered by Angular's first rendering of <em>unrelated data elsewhere on the page</em>.\nJust moving the cursor into another <code>&#x3C;input></code> triggers a call.\nRelatively few calls reveal actual changes to pertinent data.\nIf you use this hook, your implementation must be extremely lightweight or the user experience suffers.</p>\n\n \n</div>\n\n<!-- links to this doc:\n - api/core/AfterContentChecked\n - api/core/AfterContentInit\n - api/core/AfterViewChecked\n - api/core/AfterViewInit\n - api/core/ChangeDetectorRef\n - api/core/Component\n - api/core/Directive\n - api/core/DoCheck\n - api/core/OnChanges\n - api/core/OnDestroy\n - api/core/OnInit\n - errors/NG0100\n - guide/architecture-components\n - guide/architecture-next-steps\n - guide/component-interaction\n - guide/example-apps-list\n - guide/glossary\n - guide/inputs-outputs\n - guide/lightweight-injection-tokens\n - guide/module-types\n - guide/testing-components-basics\n - guide/testing-components-scenarios\n - guide/upgrade\n - tutorial/toh-pt1\n - tutorial/toh-pt4\n - tutorial/toh-pt5\n-->\n<!-- links from this doc:\n - api/common/NgForOf\n - api/core/AfterContentChecked\n - api/core/AfterContentInit\n - api/core/AfterViewChecked\n - api/core/AfterViewInit\n - api/core/Component\n - api/core/ContentChild\n - api/core/ContentChildren\n - api/core/Directive\n - api/core/DoCheck\n - api/core/Input\n - api/core/OnChanges\n - api/core/OnDestroy\n - api/core/OnInit\n - api/core/Query\n - api/core/SimpleChange\n - api/core/SimpleChanges\n - api/core/ViewChild\n - api/core/ViewChildren\n - api/core/testing/tick\n - api/forms/NgModel\n - guide/architecture\n - guide/glossary#lifecycle-hook\n - guide/glossary#unidirectional-data-flow\n - guide/glossary#view\n - guide/glossary#view-hierarchy\n - guide/lifecycle-hooks#aftercontent\n - guide/lifecycle-hooks#afterview\n - guide/lifecycle-hooks#cleaning-up-on-instance-destruction\n - guide/lifecycle-hooks#counter\n - guide/lifecycle-hooks#defining-custom-change-detection\n - guide/lifecycle-hooks#docheck\n - guide/lifecycle-hooks#general-examples\n - guide/lifecycle-hooks#initializing-a-component-or-directive\n - guide/lifecycle-hooks#lifecycle-event-sequence\n - guide/lifecycle-hooks#lifecycle-example-set\n - guide/lifecycle-hooks#lifecycle-hooks\n - guide/lifecycle-hooks#onchanges\n - guide/lifecycle-hooks#ondestroy\n - guide/lifecycle-hooks#oninit\n - guide/lifecycle-hooks#peek-a-boo\n - guide/lifecycle-hooks#prerequisites\n - guide/lifecycle-hooks#responding-to-lifecycle-events\n - guide/lifecycle-hooks#responding-to-projected-content-changes\n - guide/lifecycle-hooks#responding-to-view-changes\n - guide/lifecycle-hooks#sequence-and-frequency-of-all-lifecycle-events\n - guide/lifecycle-hooks#spy\n - guide/lifecycle-hooks#use-component-and-directive-hooks-together\n - guide/lifecycle-hooks#use-directives-to-watch-the-dom\n - guide/lifecycle-hooks#using-aftercontent-hooks\n - guide/lifecycle-hooks#using-change-detection-hooks\n - guide/lifecycle-hooks#wait-a-tick\n - guide/lifecycle-hooks#wait-before-updating-the-view\n - guide/lifecycle-hooks#write-lean-hook-methods-to-avoid-performance-problems\n - tutorial/toh-pt4#oninit\n - https://github.com/angular/angular/edit/master/aio/content/guide/lifecycle-hooks.md?message=docs%3A%20describe%20your%20change...\n - https://www.typescriptlang.org/\n-->"
}