๐น What Are Angular Lifecycle Hooks?
Angular components go through a series of phases from creation to destruction. Lifecycle Hooks let us tap into these moments and run custom logic.
Think of it like tracking an athleteโs journey:
๐ Start โ ๐ Running โ ๐ Stopping โ ๐
End of race
๐น Key Angular Lifecycle Hooks & Their Uses
1๏ธโฃ ngOnInit() - Initialization Phase
๐ Runs once when the component is created.
๐ Used for fetching API data, setting up subscriptions, or initializing values.
Example: Fetching data when the component loads.
ngOnInit() {
this.fetchUserData();
}
2๏ธโฃ ngOnChanges() - Detecting Input Changes
๐ Runs when an @Input() property changes.
๐ Useful for reacting to data updates passed from a parent component.
Example:
@Input() user: any;
ngOnChanges(changes: SimpleChanges) {
console.log('User data changed:', changes.user);
}
3๏ธโฃ ngOnDestroy() - Cleanup Before Component Removal
๐ Runs when a component is about to be removed.
๐ Used for unsubscribing from observables, clearing intervals, and releasing resources.
Example: Unsubscribing from an Observable
subscription: Subscription;
ngOnInit() {
this.subscription = this.dataService.getData().subscribe();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
๐น Other Useful Lifecycle Hooks
โ
ngDoCheck: Called during every change detection run. It allows for custom change detection and can be used to detect changes that Angularโs default mechanisms might not catch.
โ ngAfterContentInit: Called once after the componentโs content has been projected () into the view. Useful for any logic that depends on projected content.
โ ngAfterContentChecked: Invoked after every check of projected content, allowing you to respond to changes in that content.
โ ngAfterViewInit: Called once after the componentโs view and child views have been initialized. Ideal for interacting with child components or performing view-related tasks.
โ ngAfterViewChecked: Called after every check of the componentโs view. You can use this for operations that depend on the view being fully rendered.
๐น Order of the Execution of Lifecycle Hooks
๐น When to Use Lifecycle Hooks?
โ
Use ngOnInit() for initial data fetching.
โ
Use ngOnChanges() to detect @Input() changes.
โ
Use ngOnDestroy() to clean up resources and avoid memory leaks.
๐ Conclusion
Lifecycle Hooks help us control and optimize component behavior in Angular. Mastering them makes debugging and performance optimization easier!
๐ข Next, weโll explore Dependency Injection (DI) in Angular โ one of its most powerful features! Stay tuned!
Have any questions? Drop them in the comments! ๐
Top comments (0)