Understanding Angular lifecycle methods with Examples

In Angular, components have a lifecycle managed by Angular itself, from creation to destruction. Angular provides lifecycle methods that you can use to tap into this process and perform custom logic at specific points in the lifecycle.

Here are some examples of how you might use each lifecycle method:

ngOnChanges: This method is called whenever a bound input property changes. You can use it to react to changes in input properties and perform logic when the value of an input property changes.

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

@Component({
  selector: 'app-counter',
  template: '<p>{{counter}}</p>'
})
export class CounterComponent implements OnChanges {
  @Input() counter: number;

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

In this example, the CounterComponent implements the ngOnChanges method and logs the changes to its input properties.

  1. ngOnInit: This method is called after the first ngOnChanges call and is used to perform initialization logic for the component.
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-hello',
  template: '<p>Hello, {{name}}!</p>'
})
export class HelloComponent implements OnInit {
  name: string;

  ngOnInit() {
    this.name = 'Angular';
  }
}

In this example, the HelloComponent implements the ngOnInit method and initializes its name property.

  1. ngDoCheck: This method is called during every Angular change detection cycle and is used to perform custom change detection.
import { Component, DoCheck } from '@angular/core';

@Component({
  selector: 'app-todo-list',
  template: `
    <ul>
      <li *ngFor="let item of items">{{item}}</li>
    </ul>
  `
})
export class TodoListComponent implements DoCheck {
  items: string[];

  ngDoCheck() {
    console.log(this.items);
  }
}

In this example, the TodoListComponent implements the ngDoCheck method and logs its items array.

  1. ngAfterContentInit: This method is called after the component’s content has been fully initialized.
import { Component, AfterContentInit } from '@angular/core';

@Component({
  selector: 'app-tabs',
  template: `
    <ng-content></ng-content>
  `
})
export class TabsComponent implements AfterContentInit {
  ngAfterContentInit() {
    console.log('Tabs content initialized');
  }
}

In this example, the TabsComponent implements the ngAfterContentInit method and logs a message to the console.

  1. ngAfterContentChecked: This method is called after every change detection cycle that updates the component’s content. It can be used to perform logic that depends on the component’s content being fully updated and checked.
import { Component, AfterContentChecked } from '@angular/core';

@Component({
  selector: 'app-tabs',
  template: `
    <ng-content></ng-content>
  `
})
export class TabsComponent implements AfterContentChecked {
  ngAfterContentChecked() {
    console.log('Tabs content checked');
  }
}

In this example, the TabsComponent implements the ngAfterContentChecked method and logs a message to the console.

6. ngAfterViewInit: This method is called after the component’s view (including its child views) has been fully initialized.

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

@Component({
  selector: 'app-tab-panel',
  template: `
    <ng-content></ng-content>
  `
})
export class TabPanelComponent implements AfterViewInit {
  ngAfterViewInit() {
    console.log('Tab panel view initialized');
  }
}

In this example, the TabPanelComponent implements the ngAfterViewInit method and logs a message to the console.

7. ngAfterViewChecked: This method is called after every change detection cycle that updates the component’s view (including its child views).

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

@Component({
  selector: 'app-tab-list',
  template: `
    <ng-content></ng-content>
  `
})
export class TabListComponent implements AfterViewChecked {
  ngAfterViewChecked() {
    console.log('Tab list view checked');
  }
}

In this example, the TabListComponent implements the ngAfterViewChecked method and logs a message to the console.

8. ngOnDestroy: This method is called just before the component is destroyed by Angular. It can be used to perform cleanup logic for the component, such as unsubscribing from observables or detaching event handlers.

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

@Component({
  selector: 'app-timer',
  template: '<p>{{time}}</p>'
})
export class TimerComponent implements OnDestroy {
  time: number;
  intervalId: number;

  ngOnInit() {
    this.intervalId = setInterval(() => {
      this.time = Date.now();
    }, 1000);
  }

  ngOnDestroy() {
    clearInterval(this.intervalId);
  }
}

In this example, the TimerComponent implements the ngOnDestroy method and uses it to stop the interval timer it started in its ngOnInit method.

I hope you found this article useful and informative. Thanks 😊

Leave a Reply