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:

1. ngOnChanges()

Example

@Input() userId: number;

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

2. ngOnInit()

Example

ngOnInit() {
  this.loadDashboardData();
}

3. ngDoCheck()

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()

Example

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

5. ngAfterContentChecked()

Example

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

6. ngAfterViewInit()

Example

@ViewChild('inputRef') input: ElementRef;

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

7. ngAfterViewChecked()

Example

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

8. ngOnDestroy()

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

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!