DEV Community

Rating Rai
Rating Rai

Posted on

A Deep Dive into Angular Lifecycle Hooks

๐Ÿ”น 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! ๐Ÿ˜Š

Angular #WebDevelopment #Frontend #SoftwareEngineering #AngularHooks #Typescript #Hooks #LifeCycleHooks

Top comments (0)