Lifecycle hooks in Angular 2

If you haven’t already read this post LIFECYCLE HOOKS, I would highly recommend you go and read that first.

This is a really short post on just getting up and running with lifecycle hooks.

What are lifecycle hooks?

Angular 2 offers ways for our class/components to be called when certain key parts of a lifecycle workflow occur. The most obvious would be after creation, some form of initialization phase and ofcourse conversely when a class/component is cleaned up and potentially disposed of.

These are not the only lifecycle hooks, but this post is not mean’t to replicate everything in Angular 2’s documentation, but instead highlight how we use the hooks in our code.

How do we use a lifecycle hook

Let’s look at implementing a component with the two (probabaly) most used hooks, OnInit and OnDestroy, as these are obviously especially useful in situations where, maybe state needs to be loaded and stored.

As usual, we need to import the two interfaces, hence we need the line

import { OnInit, OnDestroy } from '@angular/core';

OnInit and OnDestroy look like this

export interface OnInit {
   ngOnInit() : void;
}

export interface OnDestroy {
   ngOnDestroy(): void;
}

Our component would then implement these interfaces, thus

@Component({
})
export class DetailsComponent 
      implements OnInit, OnDestroy {

   ngOnInit(): void {
   }

   ngOnDestroy(): void {
   }
}

and that’s all there is to it.

Note: In the above I said we need to import the interfaces. In reality this is not true, interfaces are optional (as they’re really a TypeScript construct to aid in type checking etc.). What Angular 2 is really looking for is the specially named methods, i.e. ngOnInit and ngOnDestroy in our case.

See LIFECYCLE HOOKS or more specifically the section on Lifecycle sequence for an understand when different parts of the life cycle hooks get called.

For completeness, I’ll list the same here, but without all the descriptions.

  • ngOnChanges
  • ngOnInit
  • ngDoCheck
  • ngAfterContentInit
  • ngAfterContentChecked
  • ngAfterViewInit
  • ngAfterViewChecked
  • ngOnDestroy