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
text
ngOnChanges (if @Input present)
β ngOnInit
β ngDoCheck
β ngAfterContentInit
β ngAfterContentChecked
β ngAfterViewInit
β ngAfterViewChecked
(then β ngDoCheck β ngAfterContentChecked β ngAfterViewChecked β cyclically)
β ngOnDestroy (when component removed)Lifecycle Hooks Usage Example
typescript
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.
Content
Main Lifecycle HooksHook Call OrderLifecycle Hooks Usage ExampleWhen to Use?
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.