Search code examples
angularangular-routingangular9angular-router

Angular 9 nested routes (3 levels)


I have nested routes with 3 levels.

Level: 1

const MAIN_ROUTE: Routes = [
  {
    path: '',
    pathMatch: 'full',
    component: AppComponent,
  },
  {
    path: 'events',
    loadChildren: () => import('../app/modules/event/event.module').then(m => m.EventModule),
  },
];
..
RouterModule.forRoot(MAIN_ROUTE);

Level: 2

const EVENT_ROUTE: Routes = [
  {
    path: '',
    component: EventComponent,
    children: {
           path: 'center',
           loadChildren: () => import('../app/modules/center/center.module').then(m => m.CenterModule),
    }
  },
  {
    path: '**',
    redircectTo: '/events/center'
    pathMatch: 'full'
  }
];
..
RouterModule.forChild(EVENT_ROUTE);

Level: 3

const CENTER_ROUTE: Routes = [
  {
    path: '',
    component: CenterComponent
  },
  {
    path: '**',
    redircectTo: ''
    pathMatch: 'full'
  }
];
..
RouterModule.forChild(CENTER_ROUTE);

I have page setup as following:

<app-main>
    <some-content></some-content>
    <router-outlet></router-outlet>
</app-main>

<app-event>
    <some-content></some-content>
    <router-outlet name="event"></router-outlet>
</app-event>

<app-center>
    <some-content></some-content>
    <router-outlet name="center"></router-outlet>
</app-center>

Whenever I navigate to /events/center, I don't see the content of CenterComponent. Did I miss anything here?


Solution

  • The reason you are seeing no content is there is no matching route in your routing modules. If your intent is to provide for multiple named outlets, you must set up a route with a matching outlet property.

    The following example is from this article about using multiple outlets.

    // use in template
    <router-outlet name="sidebar"></router-outlet>  
    
    // routing-module
    {
       path: "",
       component: SidebarComponent,
       outlet: "sidebar"  <<<<<<< add this to resolve named routes
    }
    
    

    Named routes can be useful but they get complex really fast and can create some wacky URIs. Strongly suggest trying to architect your app to keep the number of named routes to a minimum (if possible).