DEV Community

Rating Rai
Rating Rai

Posted on

1

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs