Routes paths can be both static or dynamic. Using static routes can limit angular application. Using Dynamic Routes parameters can create any numbers of dynamic routes. Like product/iphone, product/ipad or any other dynamic path followed by product/<productname> .

Angular use ActivatedRoutes service to handle dynamic routes. colon : is used for route configuration.



Dynamic Routes Example

To create dynamic routing, i am using search component for dynamic routes.

app.routes.ts

Add children property in product path, followed by pathname and component name.

           <!--app.routes.ts-->
import { Routes } from '@angular/router';
import { LoginComponent } from './login/login.component';
import { ProductComponent } from './product/product.component';
import { SearchComponent } from './search/search.component';
import { ErrorComponent } from './error/error.component';
import { HomeComponent } from './home/home.component';

        
export const routes: Routes = [
{ path: '', component:HomeComponent, pathMatch:'full'},
{ path: 'login', component:LoginComponent},
{ path:'product', component:ProductComponent},
 { path: 'search/:id', title:"Search ID", component:SearchComponent},
{ path:'**', component:ErrorComponent},
]; 

search.component.ts

Import ActivatedRoute in search.component.ts. In ngOnInit Life Cycle Hook, write the following code. I am using both Observable and snapshot with example

           <!--search.component.ts-->

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

@Component({
  selector: 'search-product',
  standalone: true,
  imports: [],
  templateUrl: './search.component.html',
  styleUrl: './search.component.css'
})
export class SearchComponent {

  x:any;

  constructor(private route:ActivatedRoute){};
  
  ngOnInit(){
  this.route.params.subscribe((p)=>{
    
    this.x=p['id'];                                 // observable, detect change
    //this.x=this.route.snapshot.params['id'];      // snapshot , read only once

    console.log(this.x);
  });
}
  
}

search.component.html

Now add the id is template.

           <!--search.component.html-->

    <p>search works!</p>

    <p>Id is : {{x}}</p>