🅰️ Angular Q40 / 125

What is ActivatedRoute and how is it used?

AI-Powered Answer ✓ Answered

ActivatedRoute is an Angular service that provides access to information about a route associated with a component that is loaded in an outlet. It allows you to retrieve route parameters, query parameters, static data, URL segments, and other route-related details.

What is ActivatedRoute?

ActivatedRoute is a crucial part of Angular's router module. When a component is activated by the router, an instance of ActivatedRoute is injected into it. This instance holds all the information about the currently active route segment, from its path to any parameters or static data defined for it.

Key Properties of ActivatedRoute

  • snapshot: A static image of the route information immediately after the route was activated.
  • params: An Observable that emits a map of required parameters extracted from the URL path.
  • queryParams: An Observable that emits a map of optional query parameters found in the URL.
  • data: An Observable that emits static data provided in the route configuration.
  • url: An Observable that emits an array of URL segments for the current route.
  • parent: The parent ActivatedRoute in the route tree.
  • firstChild: The first child ActivatedRoute in the route tree.
  • children: An array of child ActivatedRoute instances.
  • outlet: The name of the router outlet that loads this route's component.
  • routeConfig: The route configuration for the current route.

1. `snapshot`

The snapshot property provides an immediate, synchronous view of the route's parameters and data at the moment the component was activated. It's useful when you know the route parameters won't change while the component is active (e.g., navigating from /items/1 to /items/2 typically causes the component to be re-instantiated, making snapshot suitable for the initial load).

2. `params` and `queryParams`

Both params and queryParams are Observables that emit a map of parameters. params refers to parameters that are part of the route path (e.g., :id in /items/:id), while queryParams refers to optional parameters found in the URL query string (e.g., ?category=electronics). They are Observables because these parameters can change within the lifecycle of a single component instance without re-instantiation, requiring a subscription to react to changes.

3. `data`

The data property is an Observable that provides access to static data defined directly in the route configuration. This is useful for passing fixed data to a component without hardcoding it or retrieving it from a service (e.g., a page title, breadcrumb information, or configuration flags).

How to Use ActivatedRoute

To use ActivatedRoute, you typically inject it into your component's constructor. Since many of its properties are Observables, you subscribe to them to react to changes in route information, which is crucial for handling dynamic routes efficiently.

typescript
import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs';

@Component({
  selector: 'app-item-detail',
  template: '<p>Item ID: {{ itemId }}</p>'
})
export you class ItemDetailComponent implements OnInit, OnDestroy {
  itemId: string | null = null;
  private routeSubscription: Subscription | undefined;

  constructor(private route: ActivatedRoute) { }

  ngOnInit(): void {
    // Subscribing to params Observable to react to changes
    this.routeSubscription = this.route.params.subscribe(params => {
      this.itemId = params['id']; // 'id' must match the route parameter name
      console.log('Route param ID:', this.itemId);
    });

    // Accessing snapshot params for initial load (if parameter won't change)
    // const idFromSnapshot = this.route.snapshot.paramMap.get('id');
    // console.log('Snapshot ID:', idFromSnapshot);
  }

  ngOnDestroy(): void {
    // Unsubscribe to prevent memory leaks
    this.routeSubscription?.unsubscribe();
  }
}

In the example above, this.route.params.subscribe() ensures that itemId is updated whenever the id parameter in the route changes (e.g., navigating from /item/1 to /item/2 without leaving the ItemDetailComponent). It's important to unsubscribe from Observables in ngOnDestroy to prevent memory leaks.

When to Use `snapshot` vs. Observables

FeatureActivatedRouteSnapshotActivatedRoute (Observable Properties)
BehaviorProvides static, initial route information. Only reflects the state when the component was first activated.Provides dynamic, real-time updates as route parameters or query parameters change within the same component instance.
Use CaseWhen route parameters are guaranteed not to change while the component is active (e.g., a full page refresh, or navigating to a different component).When route parameters might change for the same component instance (e.g., navigating from `/users/1` to `/users/2` while staying on the `UserDetailComponent`).
MechanismSynchronous access to properties like `paramMap.get('id')`.Asynchronous subscription to Observables like `params`, `queryParams`, `data`.
Example`this.route.snapshot.paramMap.get('id');``this.route.paramMap.subscribe(params => { this.id = params.get('id'); });`

Common Use Cases

  • Fetching data based on a route ID (e.g., loading product details for /products/:id).
  • Displaying content based on query parameters (e.g., filtering search results using ?category=electronics&sort=price).
  • Accessing static route data for page titles, breadcrumbs, or configuration flags.
  • Determining the current URL segments or navigating programmatically based on parent/child routes.
  • Implementing lazy loading and resolving data before a component is activated.