Component Lifecycle Methods in Angular
Components in Angular go through series of lifecycle stages — from creation to destruction. Angular provides special methods (hooks) that allow "hooking into" these stages and executing needed logic.
Main Lifecycle Hooks
| Method (hook) | When called |
|---|---|
ngOnChanges() | When input @Input() properties change |
ngOnInit() | Once after component initialization |
ngDoCheck() | On every change detection cycle (custom change detection) |
ngAfterContentInit() | After content insertion into <ng-content> |
ngAfterContentChecked() | After each inserted content check |
ngAfterViewInit() | After view initialization (ViewChild) |
ngAfterViewChecked() | After each component view check |
ngOnDestroy() | Before component removal from DOM |
Hook Call Order
ngOnChanges (if @Input present)
→ ngOnInit
→ ngDoCheck
→ ngAfterContentInit
→ ngAfterContentChecked
→ ngAfterViewInit
→ ngAfterViewChecked
(then — ngDoCheck → ngAfterContentChecked → ngAfterViewChecked — cyclically)
→ ngOnDestroy (when component removed)
Lifecycle Hooks Usage Example
import {
Component,
OnInit,
OnChanges,
OnDestroy,
Input
} from '@angular/core';
@Component({
selector: 'app-example',
template: `<p>Lifecycle example</p>`
})
export class ExampleComponent implements OnInit, OnChanges, OnDestroy {
@Input() data: string = '';
constructor() {
console.log('constructor');
}
ngOnChanges() {
console.log('ngOnChanges: data changed');
}
ngOnInit() {
console.log('ngOnInit: component initialized');
}
ngOnDestroy() {
console.log('ngOnDestroy: component removed');
}
}
When to Use?
| Hook | What to use for |
|---|---|
ngOnInit | Data initialization, subscriptions, initial actions |
ngOnChanges | Reacting to input property changes (@Input) |
ngOnDestroy | Cleaning up timers, unsubscribing from streams, WebSocket, etc. |
ngAfterViewInit | Working with ViewChild (DOM) after display |
ngDoCheck | Custom logic on updates (rarely used) |
Tip:
Most commonly used are ngOnInit, ngOnDestroy, and ngOnChanges. Others are needed for finer tuning and specific cases.