Angular 2: Mastering the Component Lifecycle Hooks

Angular 2: Mastering the Component Lifecycle Hooks

The component lifecycle is a crucial aspect of building robust and efficient Angular applications. In this article, we will delve into the various lifecycle hooks provided by Angular, and explore their usage in a real-world scenario.

Understanding the Component Lifecycle

Components in Angular have a life cycle that consists of three primary stages: creation, update, and destruction. Each stage has its own set of lifecycle hooks that allow developers to execute specific actions at different points in the component’s life cycle.

Lifecycle Hooks: A Breakdown

Angular provides a range of lifecycle hooks that can be used to perform various tasks. Here are some of the most commonly used lifecycle hooks:

  • ngOnInit: This hook is called after the component’s initialization is complete. It is typically used to bind input attributes and execute initialization commands.
  • ngOnChanges: This hook is triggered when the input values bound to the component’s properties change. The callback method receives the current and original values of the changes object.
  • ngDoCheck: This hook is used to detect changes in the component, whether they are triggered by Angular or not. It is called each time the change detection cycle is executed.
  • ngOnDestroy: This hook is called before the component is destroyed, allowing developers to perform cleanup tasks such as unsubscribing from observables and removing event handlers to prevent memory leaks.

Order of Lifecycle Hooks

The order in which lifecycle hooks are called is as follows:

  1. ngOnInit: This hook is called after the component’s initialization is complete.
  2. ngOnChanges: This hook is triggered when the input values bound to the component’s properties change. The first call to this hook occurs after the initialization is complete.
  3. ngDoCheck: This hook is called each time the change detection cycle is executed.
  4. ngAfterContentInit: This hook is called when the projected content is inserted into the component’s view.
  5. ngAfterContentChecked: This hook is called after the projected content is checked for changes.
  6. ngAfterViewInit: This hook is called after the component’s views are initialized.
  7. ngAfterViewChecked: This hook is called after the component’s views are checked for changes.
  8. ngOnDestroy: This hook is called before the component is destroyed.

Real-World Example

To illustrate the usage of lifecycle hooks, let’s consider a simple example. Suppose we have a component that displays a list of items and allows the user to add new items. We can use the ngOnInit hook to initialize the list of items and the ngOnChanges hook to update the list when a new item is added.

import { Component, OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy } from '@angular/core';

@Component({
  selector: 'app-example',
  template: `
    <ul>
      <li *ngFor="let item of items">{{ item }}</li>
    </ul>
  `
})
export class ExampleComponent implements OnInit, DoCheck, AfterContentInit, AfterContentChecked, AfterViewInit, AfterViewChecked, OnDestroy {
  items: string[] = [];

  ngOnInit(): void {
    console.log('ngOnInit called');
  }

  ngOnChanges(changes: any): void {
    console.log('ngOnChanges called', changes);
  }

  ngDoCheck(): void {
    console.log('ngDoCheck called');
  }

  ngAfterContentInit(): void {
    console.log('ngAfterContentInit called');
  }

  ngAfterContentChecked(): void {
    console.log('ngAfterContentChecked called');
  }

  ngAfterViewInit(): void {
    console.log('ngAfterViewInit called');
  }

  ngAfterViewChecked(): void {
    console.log('ngAfterViewChecked called');
  }

  ngOnDestroy(): void {
    console.log('ngOnDestroy called');
  }

  addItem(item: string): void {
    this.items.push(item);
  }
}

In this example, we have implemented all the lifecycle hooks and added a method to add new items to the list. When the component is initialized, the ngOnInit hook is called, and when a new item is added, the ngOnChanges hook is triggered.