Discover how Angular’s component lifecycle hooks work, why they matter, and how to leverage them for robust web applications.
Table of content
If you’re building applications with Angular, understanding the component lifecycle is crucial. Lifecycle hooks provide insight and control over how Angular components are created, rendered, updated, and destroyed. Mastering these hooks helps you write more predictable and powerful apps.
Every Angular component goes through a defined series of steps from creation to removal: Instantiation, change detection, view rendering, and destruction. Angular provides lifecycle hooks—special methods—that let you tap into those moments and perform custom logic.
ngOnInit()
: Invoked once after the first ngOnChanges()
. Used for component initialization.ngOnChanges()
: Called whenever data-bound input properties change.ngDoCheck()
: Used to detect and act upon changes that Angular can’t or won’t detect on its own.ngAfterContentInit()
& ngAfterContentChecked()
: Deal with projected content (via <ng-content>
).ngAfterViewInit()
& ngAfterViewChecked()
: Focused on component’s view and its children after rendering.ngOnDestroy()
: Called just before Angular destroys the component.import { Component, OnInit, OnDestroy } from '@angular/core';
@Component({
selector: 'app-demo',
template: 'Demo works!
'
})
export class DemoComponent implements OnInit, OnDestroy {
ngOnInit() {
console.log('Component Initialized');
}
ngOnDestroy() {
console.log('Component about to be destroyed');
}
}
Hooks are called in a specific order. Here’s the typical sequence:
ngOnChanges()
(if there are bound inputs)ngOnInit()
ngDoCheck()
ngAfterContentInit()
ngAfterContentChecked()
ngAfterViewInit()
ngAfterViewChecked()
ngDoCheck()
→ ngAfterContentChecked()
→ ngAfterViewChecked()
ngOnDestroy()
ngOnInit()
: For initialization logic, API calls, or setting up your component after bindings.ngOnChanges()
: Useful when you need to react as @Input properties change.ngOnDestroy()
: For cleanup—unsubscribe from observables, remove event listeners, or clear intervals.ngOnDestroy()
to prevent memory leaks.ngOnInit()
, use ngAfterViewInit()
instead.The Angular component lifecycle offers a solid structure for building and maintaining web applications. Understanding and using lifecycle hooks effectively allows you to manage resources, optimize performance, and build scalable, maintainable code.