Search code examples
angularangular-routingangular-router

How to fix the values passed to an Angular routing parameter?


Let us say I have routing set in routings module in the below way.

  {
    path: "dashboard/project/:projectId",
    loadChildren: () =>
      import("./modules/project-details/project-details.module").then(
        (m) => m.ProjectDetailsModule
      ),
  },
  {
    path: "dashboard/project/statistics",
    loadChildren: () =>
      import("./modules/projects-statistics/projects-statistics.module").then(
        (m) => m.ProjectsStatisticsModule
      ),
  },

When I am using the routerLink in the below way, it is taking "statistics" as a value of "projectId" parameter and going to ProjectDetailsModule instead of going to ProjectsStatisticsModule.

[routerLink]="['/dashboard', 'project', 'statistics']"

How do I tell the code not to take 'statistics' as a value of 'projectId' parameter and route to ProjectsStatisticsModule instead of ProjectDetailsModule?


Solution

  • The order in which you add routes is important. Add concrete routes first and then routes with path parameters. This way the routes with path parameters is always evaluated at the last once all the concrete routes are evaluated.

    For your case, reversing the order of route declaration should yield the expected result.

    const routes = [
      {
        path: "dashboard/project/statistics",
        loadChildren: () =>
          import("./modules/projects-statistics/projects-statistics.module").then(
            (m) => m.ProjectsStatisticsModule
          ),
      },
      {
        path: "dashboard/project/:projectId",
        loadChildren: () =>
          import("./modules/project-details/project-details.module").then(
            (m) => m.ProjectDetailsModule
          ),
      }
    ];