Working with Route Parameter

Route Parameter

The route parameters are the dynamic part of the route whose value can change. These parameters provides a way to pass extra information to a given route. They are used to pass data between different components.

localhost:4200/Movies/Action/Captain-America

localhost:4200/Movies/Action/Thor

localhost:4200/Movies/Action/Thor-2

These routes are handled by:

localhost:4200/Movies/Action/:movieName

#1 Define Route Parameters

In the route configuration (usually in the AppRoutingModule), you define route parameters by specifying a placeholder in the route path.

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

In this example, :id is a route parameter representing the ID of a product.

#2 Access Route Parameters

To access route parameters within a component, inject the ActivatedRoute service and use the params property or the paramMap observable.

import { ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) { }

ngOnInit(): void {
  // Access route parameters using snapshot
  const productId = this.route.snapshot.params['id'];

  // Or subscribe to route parameter changes using observables
  this.route.params.subscribe(params => {
    const productId = params['id'];
    // Perform actions based on the route parameter
  });
}

#3 Using Route Parameters in Templates

You can also access route parameters directly in component templates using the ActivatedRoute service or the async pipe.

<p>Product ID: {{ route.snapshot.params.id }}</p>

<!-- Or using the async pipe -->
<p>Product ID: {{ (route.params | async)?.id }}</p>  

#4 Navigate with Route Parameters

When navigating to a route parameters, you can pass the parameter values as part of the navigation call.

import { Router } from '@angular/router';

constructor(private router: Router) { }

navigateToProduct(productId: number): void {
  this.router.navigate(['/products', productId]);
}

#5 Optional Route Parameters

Route parameters can be made optional by appending a question mark ? to the parameter name in the route configuration.