Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Angular FAQ: Top Questions

9. What is a lifecycle hook in Angular?

In Angular, lifecycle hooks are special callback methods that allow developers to tap into critical moments during the lifecycle of a component or directive. These hooks are part of the Angular Component Lifecycle and enable custom behavior to be executed during key phases such as initialization, change detection, and destruction.

These hooks offer developers precise control over component behavior, making them essential for building performant, responsive, and maintainable Angular applications.

  • ngOnInit() – Initialization Logic:
    • Called once the component's data-bound properties have been initialized.
    • Often used to fetch data from services, set up subscriptions, or perform one-time configuration tasks.
  • ngOnChanges() – Respond to Input Changes:
    • Called whenever input-bound properties of a component change.
    • It receives a SimpleChanges object that gives detailed information about the changes.
  • ngDoCheck() – Custom Change Detection:
    • Invoked during every change detection run, allowing for custom logic to track changes not detected by Angular’s default change detection mechanism.
  • ngAfterViewInit() – View Initialization:
    • Called once the component’s view (and its child views) has been fully initialized.
    • Useful for DOM-related logic that depends on the component’s view being rendered.
  • ngAfterViewChecked() – Post-View Check:
    • Called after the component’s view has been checked by Angular’s change detection.
  • ngOnDestroy() – Cleanup Logic:
    • Called right before Angular destroys the component.
    • Ideal for unsubscribing from observables, detaching event handlers, or cleaning up timers to prevent memory leaks.

// app.component.ts

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

@Component({
  selector: 'app-example',
  template: '<h2>Hello from ExampleComponent</h2>',
})
export class ExampleComponent implements OnInit, OnDestroy {
  intervalId: any;

  ngOnInit(): void {
    console.log('Component initialized!');
    this.intervalId = setInterval(() => {
      console.log('Running some timed task...');
    }, 1000);
  }

  ngOnDestroy(): void {
    console.log('Component is being destroyed.');
    clearInterval(this.intervalId);
  }
}
        

Explanation of the Example Code:

  • The ngOnInit() method sets up an interval timer that logs a message every second once the component is initialized.
  • The ngOnDestroy() method clears the timer when the component is about to be destroyed, demonstrating proper resource cleanup.

This example shows how lifecycle hooks can help you manage initialization and cleanup logic in a clear, declarative way, making Angular components more robust and easier to maintain.