Angular's component rendering process has a large number of facets, and different types of data and references will become available at different times. To account for this, Angular 2 allows components to set callbacks, which will be executed at different points in the component's life cycle.
The code, links, and a live example of this are available at .
Suppose you began with the following application, which simply allows the addition and removal of articles from a single input:
[app/article-list.component.ts] import {Component} from '@angular/core'; @Component({ selector: 'article-list', template: ` <input (keyup.enter)="add($event)"> <article *ngFor="let title of titles; let i = index" [articleTitle]="title"> <button (click)="remove(i)">X</button> </article> ` }) export class ArticleListComponent { titles:Array<string> = []; add(e:Event):void { this.titles.push(e.target.value); e.target.value = ''; } remove(index:number) { this.titles.splice(index, 1); } } [app/article.component.ts] import {Component, Input} from '@angular/core'; @Component({ selector: 'article', template: ` <h1> <ng-content></ng-content>{{articleTitle}} </h1> ` }) export class ArticleComponent { @Input() articleTitle:string; }
Your objective is to use life cycle hooks to keep track of the process of adding and removing operations.
Angular allows you to import hook interfaces from the core module. These interfaces are manifested as class methods, which are invoked at the appropriate time:
[app/article.component.ts] import {Component, Input, ngOnInit, ngOnDestroy} from '@angular/core'; @Component({ selector: 'article', template: ` <h1> <ng-content></ng-content>{{articleTitle}} </h1> ` }) export class ArticleComponent implements OnInit, OnDestroy { @Input() articleTitle:string; ngOnInit() { console.log('created', this.articleTitle); } ngOnDestroy() { console.log('destroyed', this.articleTitle); } }
With this, you should see logs each time a new ArticleComponent
is added or removed.
Different hooks have different semantic meanings, but they will occur in a well-defined order. Each hook's execution guarantees that a certain behavior of a component is just completed.
The hooks that are currently available to you in the order of execution are as follows:
ngOnChanges
ngOnInit
ngDoCheck
ngAfterContentInit
ngAfterContentChecked
ngAfterViewInit
ngAfterContentChecked
ngOnDestroy
It is also possible for third-party libraries to extend these and add their own hooks.
Using hooks is optional, and Angular will only invoke them if you have defined them. The use of the implements
interface declaration is optional, but it will signal to the TypeScript compiler that a corresponding method should be expected, which is obviously a good practice.
ViewChild
to reference child component object instancesContentChild
to reference child component object instances