Home > OS >  angular how to use nested child routing?
angular how to use nested child routing?

Time:11-22

In my app-routing.module.ts I load my children

  {
    path: 'account',
    loadChildren: () => import('./components/account/account.module').then((esm) => esm.AccountModule)
  },

then I have my child account-routing.module.ts

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: '',
        component: AccountComponent,
      },
      {
        path: ':accountname',
        component: ViewAccountComponent,

        children: [
          {
            path: ':userid',
            component: ViewUserComponent
          }
        ]
      },
    ]
  }
];

Whenever I call for exmaple account/testaccountName/123I my ViewUserComponent won´t be called, instead my ViewAccountComponent will be called even though ViewUserComponent is a child of ViewAccountComponent. A solution would be to put my ViewUserComponent on the same level as the ViewAccountComponent (without children[]) like this

{
    path: ':accountid',
    component: ViewAccountComponent
},
{
    path: ':accountid/:userid',
    component: ViewUserComponent
}

but I would like to keep my children [].

CodePudding user response:

Is the router-outlet directive present in your ViewAccountComponent template? Otherwise, nested routing won't work.

CodePudding user response:

Nested routes are a way to render data hierarchically. This means first the parent will be rendered in the router-outlet and afterwards the corresponding child route will be rendered in the router-outlet contained in the parent component. This is the reason why there are child routes at all.

If you don't want to have this hierarchical view in your DOM, you should not use routes defined as children in your route config. They should then be at the same level.

You now have two options to get the matching work correctly. Either you change the routes order, so that for the more specific route the matching will be done before the less specific route like in the following example:

{
    path: ':accountid/:userid',
    component: ViewUserComponent
},
{
    path: ':accountid',
    pathMatch: 'full',
    component: ViewAccountComponent
}

Or you can set pathMatch: 'full' in order to only match if no path segments are following the less specific route:

{
    path: ':accountid',
    pathMatch: 'full',
    component: ViewAccountComponent
},
{
    path: ':accountid/:userid',
    component: ViewUserComponent
}
  • Related