Understanding Angular’s lifecycle hooks is crucial for developers to manage components and build robust angular applications effectively. Angular offers a set of

Angular Component Lifecycle Overview

  • Explain the lifecycle stages of an Angular component: creation, rendering, and destruction.
  • Introduce the concept of lifecycle hooks, which are methods provided by Angular that allow developers to tap into these lifecycle stages.
  • Mention that each hook corresponds to a specific lifecycle event.

1. ngOnChanges()

The ngOnChanges hook is called when one or more input properties of a component change. Updating your component’s state is made convenient by responding to input changes.

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnChanges {
  @Input() inputMessage: string = '';

  ngOnChanges(changes: SimpleChanges): void {
    console.log(changes);
  }
}

NOTE:
If your component has no inputs or you use it without providing any inputs, the framework will not call ngOnChanges()

2. ngOnInit()

This Hook is called After Angular has displayed the data-bound properties and set the input properties of a directive or component, initialize it.

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

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css'],
})
export class HomeComponent implements OnInit {
  ngOnInit(): void {
    console.log('OnInit Called');
  }
}

Here, we initialize the console log OnInit Called property when the component is first created.

3. ngDoCheck()

Angular may not always be able to detect or address changes on its own. In such cases, it is important to identify and respond to these changes.

import { Component, DoCheck } from '@angular/core';

@Component({
  selector: 'app-example',
  template: '<p>{{ message }}</p>'
})
export class ExampleComponent implements DoCheck {
  message: string = 'Initial Message';

  ngDoCheck() {
    console.log('DoCheck triggered');
    // Custom change detection logic here
  }
}

4. ngAfterContentInit()

This hook is called after Angular projects external content into the component’s view.

import { Component, AfterContentInit } from '@angular/core';

@Component({
  selector: 'app-example',
  template: '<ng-content></ng-content>',
})
export class ExampleComponent implements AfterContentInit {
  ngAfterContentInit(): void {
    // Access and initialize content children here.
  }
}

5. ngAfterContentChecked()

This hook is called after Angular checks the content projected into the component.

import { Component, AfterContentChecked } from '@angular/core';

@Component({
  selector: 'app-example',
  template: '<ng-content></ng-content>'
})
export class ExampleComponent implements AfterContentChecked {
  ngAfterContentChecked() {
    console.log('AfterContentChecked triggered');
    // Additional logic after content is checked
  }
}

6. ngAfterViewInit()

After the component’s views and child views, or the view containing the directive have been initialized

import { Component, AfterViewInit, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-example',
  template: '<div #myDiv></div>',
})
export class ExampleComponent implements AfterViewInit {
  @ViewChild('myDiv') myDiv!: ElementRef;

  ngAfterViewInit(): void {
    // Access and manipulate the DOM element here.
  }
}

7. ngAfterViewChecked()

The ngAfterViewChecked hook is called after every change detection cycle once the view and child views are checked. This can be utilized for performing extra actions once the view has been checked.

import { Component, AfterViewChecked } from '@angular/core';

@Component({
  selector: 'app-example',
  template: '<p>{{ message }}</p>',
})
export class ExampleComponent implements AfterViewChecked {
  message: string = '';

  ngAfterViewChecked(): void {
    // Additional actions after the view has been checked.
  }
}

8. OnDestroy()

Clean up just before Angular destroys the directive or component by unsubscribing Observables and detaching event handlers to prevent memory leaks.

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

@Component({
  selector: 'app-example',
  template: '<p>{{ message }}</p>'
})
export class ExampleComponent implements OnDestroy {
  message: string = 'Initial Message';
  intervalId: any;

  constructor() {
    this.intervalId = setInterval(() => {
      this.message = new Date().toLocaleTimeString();
    }, 1000);
  }

  ngOnDestroy() {
    console.log('Component destroyed');
    clearInterval(this.intervalId);
  }
}

Conclusion

  • Recap of the importance of understanding the Angular component lifecycle.
  • Encouragement for further exploration and experimentation with lifecycle hooks in Angular applications.

QUIZ GAME