Angular — Lifecycle
Lifecycle Hooks
| Hook | When Called |
|---|---|
| constructor | Class instantiation |
| ngOnInit | After first ngOnChanges |
| ngOnChanges | When input properties change |
| ngDoCheck | Custom change detection |
| ngAfterContentInit | Content projected |
| ngAfterContentChecked | Content checked |
| ngAfterViewInit | View initialized |
| ngAfterViewChecked | View checked |
| ngOnDestroy | Before destruction |
Example
import { Component, OnInit, OnChanges, OnDestroy,
AfterViewInit, SimpleChanges } from '@angular/core';
@Component({
selector: 'app-lifecycle',
template: `<p>{{message}}</p>`
})
export class LifecycleComponent implements OnInit, OnChanges, OnDestroy, AfterViewInit {
@Input() data: any;
message = 'Hello';
constructor() {
console.log('Constructor');
}
ngOnChanges(changes: SimpleChanges) {
console.log('Changes:', changes);
}
ngOnInit() {
console.log('Initialized');
}
ngAfterViewInit() {
console.log('View ready');
}
ngOnDestroy() {
console.log('Destroyed');
}
}
Common Use Cases
| Hook | Use Case |
|---|---|
| ngOnInit | Fetch data, initialize |
| ngOnChanges | React to input changes |
| ngOnDestroy | Cleanup subscriptions |
| ngAfterViewInit | Access child components |
Mini Practice
- Implement all lifecycle hooks
- Log lifecycle events
- Fetch data in ngOnInit
- Clean up in ngOnDestroy
Up Next
Continue with Composition API — Angular composition patterns.
Related Topics
Frequently Asked Questions about Lifecycle
What is Lifecycle in Angular?
Lifecycle is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Lifecycle?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Lifecycle.
Why is Lifecycle important in Angular?
Lifecycle is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.