Component Lifecycle
Every component in Angular goes through a series of phases from creation to destruction. These are called lifecycle hooks. Think of them like the stages of a plant: seed, sprout, grow, flower, and wither. Angular lets you tap into these stages to run custom logic.
Here are the most important lifecycle hooks in order:
- ngOnChanges – Called when input properties change.
- ngOnInit – Called once after the first ngOnChanges. Great for initialization.
- ngDoCheck – Called during every change detection run.
- ngAfterContentInit – Called after content projection.
- ngAfterContentChecked – Called after every check of projected content.
- ngAfterViewInit – Called after component's view and child views are initialized.
- ngAfterViewChecked – Called after every check of component's view.
- ngOnDestroy – Called just before component is destroyed. Great for cleanup.
Example showing the most commonly used hooks:
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
@Component({
selector: 'app-lifecycle-demo',
template: `<p>Lifecycle component: {{ data }}</p>`
})
export class LifecycleDemoComponent implements OnInit, OnDestroy {
@Input() data: string;
constructor() {
console.log('Constructor called');
}
ngOnInit() {
console.log('ngOnInit called - Component initialized');
}
ngOnDestroy() {
console.log('ngOnDestroy called - Cleaning up');
}
}
Two Minute Drill
- Lifecycle hooks let you run code at specific times in a component's life.
- ngOnInit is for initialization logic (most commonly used).
- ngOnDestroy is for cleanup (unsubscribing from observables, clearing timers).
- Implement the interface for each hook you want to use (e.g., OnInit, OnDestroy).
- Hooks help you control component behavior precisely.
Need more clarification?
Drop us an email at career@quipoinfotech.com
