Angular  

Understanding Angular Lifecycle Hooks

Introduction

Angular components go through a lifecycle from creation to destruction. Understanding this lifecycle is crucial for writing clean, efficient, and bug-free Angular applications. Angular provides lifecycle hooks that allow developers to tap into these key moments, such as initialization, change detection, and destruction.

In this article, we'll explore the most commonly used Angular lifecycle hooks with practical examples and real-world use cases.

What Are Lifecycle Hooks?

Lifecycle hooks are special TypeScript methods that Angular calls automatically at specific points in a component's lifecycle.

They are defined in Angular’s core and include:

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

1. ngOnChanges()

  • Purpose: Called when any data-bound property (@Input()) changes.
  • Timing: Runs before ngOnInit() and whenever an input changes thereafter.
  • Use Case: Useful when a parent component updates an input value, and the child needs to act on it.

Example

@Input() userId: number;

ngOnChanges(changes: SimpleChanges) {
  if (changes.userId) {
    this.fetchUser(changes.userId.currentValue);
  }
}

2. ngOnInit()

  • Purpose: Called once after the component is initialized.
  • Timing: After the first ngOnChanges().
  • Use Case: Initialize component data (like API calls, default values, subscriptions).

Example

ngOnInit() {
  this.loadDashboardData();
}

3. ngDoCheck()

  • Purpose: Called during every change detection cycle.
  • Timing: After ngOnChanges() and ngOnInit(), and on every change thereafter.
  • Use Case: Custom change detection logic (e.g., detecting changes in deep objects or arrays).

Example

ngDoCheck() {
  if (this.previousLength !== this.items.length) {
    this.previousLength = this.items.length;
    this.onListLengthChanged();
  }
}

Note. Use with caution, as it can lead to performance issues.

4. ngAfterContentInit()

  • Purpose: Called once after Angular projects external content into the component.
  • Timing: After content has been initialized via ng-content.
  • Use Case: Manipulating projected content.

Example

ngAfterContentInit() {
  console.log('Content projected!');
}

5. ngAfterContentChecked()

  • Purpose: Called after every check of the projected content.
  • Timing: After every change detection cycle for ng-content.
  • Use Case: Debugging or Verifying Content Changes.

Example

ngAfterContentChecked() {
  console.log('Projected content checked.');
}

6. ngAfterViewInit()

  • Purpose: Called once after the component’s view (and child views) are initialized.
  • Timing: After Angular sets up the DOM, including @ViewChild queries.
  • Use Case: Interacting with DOM elements.

Example

@ViewChild('inputRef') input: ElementRef;

ngAfterViewInit() {
  this.input.nativeElement.focus(); // Safe to access now
}

7. ngAfterViewChecked()

  • Purpose: Called after every check of the component’s views.
  • Timing: After Angular updates the view and child views.
  • Use Case: Responding to changes in the component’s view (use sparingly).

Example

ngAfterViewChecked() {
  console.log('View checked.');
}

8. ngOnDestroy()

  • Purpose: Called just before Angular destroys the component.
  • Timing: Before component removal from the DOM.
  • Use Case: Cleanup logic like unsubscribing Observables, detaching event listeners, and clearing timers.

Example

subscription: Subscription;

ngOnInit() {
  this.subscription = this.dataService.getData().subscribe(...);
}

ngOnDestroy() {
  this.subscription.unsubscribe(); // Prevent memory leaks
}
Hook Triggered When... Common Use
ngOnChanges Input property changes Respond to input changes
ngOnInit The component is initialized Fetch data, set up
ngDoCheck Every change detection cycle Custom change tracking
ngAfterContentInit External content is projected Handle ng-content
ngAfterContentChecked Projected content checked Debug content projection
ngAfterViewInit Component’s view initialized DOM manipulation
ngAfterViewChecked Component’s view checked View debugging
ngOnDestroy The component is about to be destroyed Cleanup

Best Practices

  • Prefer ngOnInit over constructor() for initialization logic.
  • Always clean up in ngOnDestroy() to prevent memory leaks.
  • Use ngDoCheck and ngAfterViewChecked only when necessary due to performance cost.
  • Keep each lifecycle hook focused, and avoid cluttering with unrelated logic.

Conclusion

Understanding and using Angular’s lifecycle hooks gives you deeper control over your component behavior, especially when dealing with asynchronous data, view rendering, or external libraries.

Whether you’re initializing data, responding to changes, or cleaning up resources, lifecycle hooks help ensure your Angular app remains performant and maintainable.

Happy coding!

OSZAR »