Search code examples
angularangular-routing

Angular: nested router-outlet is always ignored


Do you have any idea what might be wrong with my configuratoin if my second router-outlet is always ignored? This here is my app.module routing (app.component has one router-outlet):

const routes: Routes = [
  {
    path: 'home',
    loadChildren: './home/home.module#HomeModule',
    canLoad: [AuthorizationGuard]
  },
  {
    path: 'please-login',
    component: PleaseLoginComponent
  },
  {
    path: '**',
    redirectTo: 'please-login'
  }
];

And here is my home.module-routing (HomeComponent has another router-outlet):

RouterModule.forChild([
  {
    path: '',
    pathMatch: 'full',
    component: HomeComponent,
    children: [
      {
        path: 'welcome',
        component: WelcomeComponent
      }
    ]
  },
  {
    path: '**',
    redirectTo: 'welcome'
  },
  {
    path: 'Data',
    loadChildren: '@libs/data#DataModule'
  }
]),

I can load DataModule with no problems; it directs me to /home/data/blabla. But (!) it inserts DataComponent into the first router-outlet. The second one (and thus the whole HomeComponent which is supposed to surround DataComponent) is ignored. That is, unless I navigate to /home, then it is displayed, but as expected, with no DataComponent inside. Meaning I can use both components only exclusively and not nested.

I tried using named outlets, but to no success. When I trace-log the router-state, the resolves seem to be ok, so I am a bit lost here


Solution

  • To make the DataComponent load in the router-outlet of the HomeComponent(which means you'll have to add a <router-outlet></router-outlet> to your HomeComponent template as well), you will have to make data as a child of the '' path.

    Another thing that you'll have to do is remove pathMatch: 'full' from your '' route. What it would do is, try to match the path in chunks, i.e. if '' is matched, it will try to check for any matching child routes.

    Finally, I'm not sure if it's a typo or not, but the path should be data and NOT Data.

    All this would translate to code something like this:

    RouterModule.forChild([
      {
        path: '',
        component: HomeComponent,
        children: [
          {
            path: 'data',
            loadChildren: '@libs/data#DataModule'
          },
          {
            path: 'welcome',
            component: WelcomeComponent
          },
          {
            path: '**',
            redirectTo: '/welcome',
            pathMatch: 'full'
          }
        ]
      },
      ...
    ]),