Search code examples
angularangular-routing

Angular 6 routing - setting children route component based on parent route parameters


I have the following routing configuration in my Angular 6 project.

    path: 'chart/:feature',
    component: ChartStateComponent,
    canActivateChild: [ChartGuardService],
    children: [
        {
            path: ':id',
            redirectTo: '/chart/:feature/:id/profile',
            pathMatch: 'full'
        },
        {   path: ':id/:tab',
            component: TestOneComponent,
            pathMatch: 'full'
        }
    ]

feature is param to parent path and it can 4 different values like one, two, three and four. Now depending on this param, I need to set the component for children path.

For example, if feature is set one, then set TestOneComponent as children component.

How can i achieve this?


Solution

  • You could try this:

    path: 'chart',
    component: ChartStateComponent,
    canActivateChild: [ChartGuardService],
    children: [
        {
            path: 'one/:id',
            redirectTo: 'one/:id/profile',
            pathMatch: 'full'
        },
        {   path: 'one/:id/:tab',
            component: TestOneComponent
        },
        {   path: 'two/:id/:tab',
            component: TestTwoComponent
        },
        ...
    ],
    

    Alternatively, you could build a route guard to handle more complex routing. See this question for more information: Angular2 conditional routing

    UPDATE

    I'm not sure how you could add a conditional based on the parameter ... but you can add a conditional based on a global variable.

    In a "Globals" file:

     export class Globals {
        public static ISADMIN: boolean = false;
     }
    

    In your module route definitions

      {
        path: 'products/:id',
        component: Globals.ISADMIN ?  ProductAdminComponent : ProductDetailComponent
      },