An optional route parameter allows you to define a parameter that might or might not be present in the URL. You can make the route parameter optional by using ? in the route path.

1. Define the Route with an Optional Parameter

In app-routing.module.ts, use :param? to define an optional parameter:

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EmployeeComponent } from './employee/employee.component';
import { PageNotFoundComponent } from './page-not-found/page-not-found.component';
 
const routes: Routes = [
  { path: '', component: EmployeeComponent },
  { path: 'employee/:id/:name/:role?', component: EmployeeComponent }, // Optional 'role' parameter
  { path: '**', component: PageNotFoundComponent } // Wildcard route for 404
];
 
@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}

2. Access Optional Parameter in Component

In the EmployeeComponent, you can access the optional parameter using ActivatedRoute:

// employee.component.ts
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
 
@Component({
  selector: 'app-employee',
  templateUrl: './employee.component.html'
})
export class EmployeeComponent implements OnInit {
  employeeId: string | null = null;
  employeeName: string | null = null;
  employeeRole: string | null = null;
 
  constructor(private route: ActivatedRoute) {}
 
  ngOnInit(): void {
    this.route.params.subscribe(params => {
      this.employeeId = params['id'];
      this.employeeName = params['name'];
      this.employeeRole = params['role'] || 'Not Assigned'; // Default if role is not provided
    });
  }
}

3. Template for Displaying Data

In the template, you can display the employee details, including the optional role:

<!-- employee.component.html -->
<h1>Employee Details</h1>
<p>Employee ID: {{ employeeId }}</p>
<p>Employee Name: {{ employeeName }}</p>
<p>Employee Role: {{ employeeRole }}</p>

4. Navigating with Optional Parameters

When you navigate to a route with or without the optional parameter, it will still work:

<!-- app.component.html -->
<a [routerLink]="['/employee', 123, 'John Doe']">Employee 123 (No Role)</a>
<br>
<a [routerLink]="['/employee', 124, 'Jane Smith', 'Manager']">Employee 124 (With Role)</a>
<router-outlet></router-outlet>

Summary:

  • Use :param? in the route to define an optional parameter.
  • The optional parameter can be accessed with ActivatedRoute in the component.
  • If the parameter is not provided, you can assign a default value in the component.

This setup allows you to pass values with the route parameters while making one of them optional.