Angular-Hook into the Component Lifecycle
In Angular, every component has a lifecycle — a series of steps it goes through from creation to destruction.
Angular provides lifecycle hooks, which are special methods you can implement to run code at key moments in that lifecycle.
🧩 List of Angular Lifecycle Hooks (in order)
Lifecycle HookWhen It’s CalledCommon Use
ngOnChanges()When input properties (@Input) changeRespond to changes in input data
ngOnInit()Once after the first
ngOnChanges()Initialize data, fetch API data
ngDoCheck()During every change detection runDetect and act on changes not handled by Angular
ngAfterContentInit()After content (ng-content) is projected into the componentInitialize projected content
ngAfterContentChecked()After every check of projected contentRespond after content changes
ngAfterViewInit()After component’s view (and child views) are initializedAccess child elements, view references
Get Roshani Shah’s stories in your inbox
Join Medium for free to get updates from this writer.
ngAfterViewChecked()After every check of the component’s viewPerform actions after view updates
ngOnDestroy()Just before Angular destroys the componentClean up (unsubscribe, remove listeners)
import { Component, Input, OnInit, OnChanges, OnDestroy } from '@angular/core';
@Component({
selector: 'app-user-card',
template: `
<h3>{{ user.name }}</h3>
`
})
export class UserCardComponent implements OnInit, OnChanges, OnDestroy {
@Input() user: any;
constructor() {
console.log('Constructor: Component instance created');
}
ngOnChanges() {
console.log('ngOnChanges: Input property changed');
}
ngOnInit() {
console.log('ngOnInit: Component initialized');
}
ngOnDestroy() {
console.log('ngOnDestroy: Component about to be destroyed');
}
}⚙️ Typical Lifecycle Flow
For a component with @Input() properties:
Constructor → ngOnChanges() → ngOnInit() → ngDoCheck() →
ngAfterContentInit() → ngAfterContentChecked() →
ngAfterViewInit() → ngAfterViewChecked() → ngOnDestroy()✅ Best Practices
- Use
ngOnInit()for initialization logic (not in constructor). - Use
ngOnDestroy()to unsubscribe from Observables or remove event listeners. - Avoid heavy logic in
ngDoCheck()— it runs frequently. - Access DOM or
@ViewChild()elements only afterngAfterViewInit().





