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

  1. 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;  
      });  
    }  
    
  2. 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;  
      }  
    }  
    
  3. ngOnInitComplete
    Called after ngOnInit and ngOnChanges are completed. Suitable for final setup, such as rendering UI components.

  4. 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();  
    }  
    
  5. 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: ngOnInit and ngOnChanges are triggered.
  • Navigation: ngOnDestroy ensures cleanup when the route is no longer active.
  • Deactivation: canDeactivate handles user interactions, such as saving data before leaving a component.

Best Practices

  • Avoid memory leaks: Use ngOnDestroy to unsubscribe from observables or timers.
  • Lazy loading: Leverage lazyLoad for performance optimization.
  • Error handling: Implement onError in ngOnInit to manage failures gracefully.

Real-World Applications

  • Data Fetching: ngOnInit is used to load initial data, while canDeactivate ensures data is saved before navigation.
  • Subscription Management: ngOnDestroy unsubscribes from API calls to prevent memory leaks.
  • Component State: ngOnChanges updates UI based on dynamic inputs, such as a search term.

By mastering these hooks, developers can ensure robust, efficient, and maintainable Angular applications.