Angular - Dynamic Routes


This chapter will discuss, what is dynamic routes in Angular, including its syntax, usage and example of using in real-time Angular project.

Dynamic Routes in Angular

In Angular, dynamic routes are used to load a specific data or entity within a component based on the route parameters.

For example, in a streaming platform having multiple videos, the application could use dynamic routes to load each video within the VideosComponent by passing the video ID as a route parameter.

This way, each time a user navigates to a new video (e.g., /videos/:id), the corresponding video data is fetched and displayed dynamically.

Note: Dynamic routing refers to the overall technique or approach of implementing dynamic routes.

Syntax of Angular Dynamic Routes

Below is the syntax to create Dynamic Routes in Angular −

const routes: Routes = [
  { path: 'route-path/:parameterName', component: SomeComponent }
];

Here,

  • route-path: This represents the name of the route path that will be used to access the current component.
  • parameterName: The name of the parameter that you want to access, such as id.
  • SomeComponent: The name of the component that should be loaded based on the current path and parameter.

The 'parameterName' can be accessed in the component using two techniques, which are:

  • Using Observable.
  • Using snapshot (non-observable option).

Using Observable

Angular provides a special interface named paramMap to access the parameters of the path (URL). parmaMap has the following methods −

  • has(name): Returns true if the specified name is available in the path (parameter list).

  • get(name): Returns the value of the specified name in the path (parameter list).

  • getAll(name): Returns the multiple value of the specified name in the path. The get() method returns only the first value when multiple values are available.

  • keys: Returns all parameters available in the path.

The Steps to access the parameter using paramMap are as follows −

  • Import paramMap available in @angular/router package.

  • Use paramMap in the ngOnInit() to access the parameter and set it to a local variable.

ngOnInit() {
    this.route.paramMap.subscribe(params => {
        this.parameterName = params.get('parameterName);
    });
}

We can use it directly in the rest service using the pipe method.

this.item$ = this.route.paramMap.pipe(
    switchMap(params => {
      this.selectedId = Number(params.get('parameterName'));
      return this.service.getItem(this.selectedId);
    })
);

Using snapshot

The snapshot is similar to Observable, but it does not support observable and gets the parameter value immediately.

let id = this.route.snapshot.paramMap.get('parameterName');

Example of Angular Dynamic Routes

Below is a example of using the Dynamic Routes in a Angular project −

Step 1: Define dynmiac route

import { Routes } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ViewItemComponent } from './view-item/view-item.component';

export const routes: Routes = [
    {path: 'home', component: HomeComponent},
    {path: 'about', component: AboutComponent},
    {path: 'view/:id', component: ViewItemComponent}
];

Step 2: Add your routes to your application

<h1>Angular Routing</h1>
<a routerLink="/home">Home</a><br>
<a routerLink="/about">About</a>
<a routerLink="/view/1">View Item1</a><br>
<a routerLink="/view/2">View Item2</a>
<router-outlet></router-outlet>

Step 3: Access 'id' parameter in ViewItemComponent

import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-view-item',
  imports: [],
  templateUrl: './view-item.component.html',
  styleUrl: './view-item.component.css'
})
export class ViewItemComponent implements OnInit{
  id: any;
  constructor(private route: ActivatedRoute){}
  ngOnInit(): void {
      this.route.paramMap.subscribe(res=>{
        this.id = res.get('id');
      });
  }
}

Step 4: Display the current Item based on it's id

<p>View item{{id}}</p>

Now run the application and see the output:

Dynamic Routes

By observing the URL in the above GIF, you can clearly see that the items are loaded dynamically based on changes to their ID parameter in the routes.