Angular Route Lifecycle Hooks
Angular’s route configuration involves managing the lifecycle of components and routes, ensuring proper initialization, navigation, and destruction. Key lifecycle hooks are critical for handling state, subscriptions, and resource management.
Route Lifecycle Overview
Angular’s route configuration defines the sequence of events when a route is activated, navigated, or destroyed. These hooks enable developers to perform actions such as data fetching, subscription management, or UI updates at specific points in the lifecycle.
Core Lifecycle Hooks
ngOnInit
Called once when the route is activated. Ideal for initializing components, setting up subscriptions, or fetching data.ngOnInit(): void { this.apiService.getData().subscribe(data => { this.data = data; }); }ngOnChanges
Triggered when input properties change. Useful for updating component state based on dynamic data.ngOnChanges(changes: SimpleChanges): void { if (changes.title) { this.title = changes.title.currentValue; } }ngOnInitComplete
Called afterngOnInitandngOnChangesare completed. Suitable for final setup, such as rendering UI components.ngOnDestroy
Invoked when the component is destroyed. Used to unsubscribe from subscriptions, clear timers, or release resources.ngOnDestroy(): void { this.subscription.unsubscribe(); this.timer.clear(); }canDeactivate
Called when the route is deactivated (e.g., navigation back or form submission). Enables custom logic for user confirmation or data saving.canDeactivate(): boolean { return this.formService.isFormValid(); }
Route Context Lifecycle
Angular’s route lifecycle includes:
- Activation:
ngOnInitandngOnChangesare triggered. - Navigation:
ngOnDestroyensures cleanup when the route is no longer active. - Deactivation:
canDeactivatehandles user interactions, such as saving data before leaving a component.
Best Practices
- Avoid memory leaks: Use
ngOnDestroyto unsubscribe from observables or timers. - Lazy loading: Leverage
lazyLoadfor performance optimization. - Error handling: Implement
onErrorinngOnInitto manage failures gracefully.
Real-World Applications
- Data Fetching:
ngOnInitis used to load initial data, whilecanDeactivateensures data is saved before navigation. - Subscription Management:
ngOnDestroyunsubscribes from API calls to prevent memory leaks. - Component State:
ngOnChangesupdates UI based on dynamic inputs, such as a search term.
By mastering these hooks, developers can ensure robust, efficient, and maintainable Angular applications.