In Angular applications, route data plays a crucial role in enriching routes with additional data and information that can be accessed during navigation. It allows developers to attach metadata to routes, which can be used to configure views or pass specific settings without cluttering the codebase. Angular provides various ways to handle route data depending on the requirements of your application. These approaches help in making route-specific information accessible and manageable.

1. Using Route data Property in the Route Configuration

This is the most straightforward way to pass static data.
Example:

const routes: Routes = [
  {
    path: 'example',
    component: ExampleComponent,
    data: { message: 'Hello, Angular!' }
  }
];

Access in Component:

import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {}
ngOnInit() {
  const message = this.route.snapshot.data['message'];
  console.log(message); // Output: Hello, Angular!
}

This approach involves adding static data directly to the route configuration. The data is defined in the data property of a route object. This method is ideal for passing constant or predefined data.

How it works:

  • Static data is added in the route definition under the data key.
  • The component retrieves the data using the ActivatedRoute service.
  • The snapshot or data observables can be used to access the provided data.

2. Passing Parameters in the URL

You can pass dynamic data via route parameters.
Example:

const routes: Routes = [
  { path: 'example/:id', component: ExampleComponent }
];

Navigating:

this.router.navigate(['/example', 18]);

Access in Component:

this.route.params.subscribe(params => {
  const id = params['id'];
  console.log(id); // Output: 18
});

Dynamic data can be passed through the URL as route parameters. This is especially useful when the data is a part of the resource’s identity (e.g., an ID).

How it works:

  • Define route parameters in the route path using :parameterName.
  • Use Router to navigate and pass the required values.
  • Retrieve the parameters in the target component using ActivatedRoute.params.

3. Using Query Parameters

Query parameters are suitable for optional data.

Example:

this.router.navigate(['/example'], { queryParams: { page: 1, size: 10 } });

Access in Component:

this.route.queryParams.subscribe(params => {
  console.log(params['page']); // Output: 1
});

Query parameters allow optional or additional data to be passed with the URL. Unlike route parameters, they are not tied to the route structure.

How it works:

  • Pass key-value pairs as query parameters using Router.navigate or navigateByUrl.
  • Extract query parameters in the target component using ActivatedRoute.queryParams.
  • This approach is suitable for filtering or pagination data.

4. Using State (Introduced in Angular 7.2)

State allows data to be passed directly during navigation without appearing in the URL.
Example:

this.router.navigateByUrl('/example', { state: { message: 'Hello from state!' } });

Access in Component:

const state = this.router.getCurrentNavigation()?.extras.state;
console.log(state?.message); // Output: Hello from state!

State enables passing data directly during navigation without appending it to the URL. This method is suitable for sensitive or temporary data.

How it works:

  • Pass the data using the state property of the NavigationExtras object.
  • Retrieve the data in the target component usingRouter.getCurrentNavigation()?.extras.state.
  • The state is cleared once the navigation completes.

5. Using a Shared Service

This approach is particularly useful when data does not need to be reflected in the URL
Example:

@Injectable({ providedIn: 'root' })
export class DataService {
  private data: any;
  setData(data: any) { this.data = data; }
  getData() { return this.data; }
}

Access in Component:

// Component 1 (Source)
this.dataService.setData({ value: 'Shared Data' });
this.router.navigate(['/example']);

// Component 2 (Target)
const data = this.dataService.getData();
console.log(data.value); // Output: Shared Data

A shared service can act as a central store for passing data between components during navigation.

How it works:

  • Create a service to store and retrieve shared data.
  • Inject the service into both the source and destination components.
  • Update the data in the service before navigation and retrieve it in the target component.

Conclusion

Selecting the right approach to manage Angular route data is key to building scalable and maintainable applications. By understanding and leveraging these techniques, developers can efficiently configure routes and enhance application functionality.

Support On Demand!

Angular

Related Q&A