7
votes

Not sure do I do everything right. But the thing is: when I navigate to some child routes of component from lazy loaded module it simply does not load. It reloads home component from Lazy Loaded Module.

app-routing.component.ts

const routes: Routes = [
  {path: 'intel', loadChildren: () => import(`./intel/intel.module`).then(m => m.IntelModule)},
  {
    path: 'planet-detector',
    loadChildren: () => import('./planet-detector/planet-detector.module').then((m) => m.PlanetDetectorModule)
  },
  {path: '', redirectTo: 'space', pathMatch: 'full'},
  {path: '**', component: BlackHoleComponent}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

planet-detector-routing.module.ts

const routes: Routes = [
  {path: '', component: DetectorComponent, children: [
      { path: 'first', component: FirstChildComponent},
      { path: 'second', component: SecondChildComponent}
    ]}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class PlanetDetectorRoutingModule { }

So in the example as above when you put: 'http://localhost:4200/planet-detector/first' it loads DetectorComponent component instead of FirstChildComponent (url points to 'http://localhost:4200/planet-detector/first').

I noticed that when I change PlanetDetectorRoutingModule to:

const routes: Routes = [
  { path: '', component: DetectorComponent },
  { path: 'first', component: FirstChildComponent },
  { path: 'second', component: SecondChildComponent }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class PlanetDetectorRoutingModule { }

Then it works fine. And mb one more question. What are the benefits of these children route separation?

1

1 Answers

8
votes

When routes are declared in the children property, it means that they should be rendered as a child of that component.

So for that route to be rendered, there needs to be a <router-outlet> in the DetectorComponent.

Routes listed in children follow this rule:

There are important differences in the way the router treats these child routes.

The router displays the components of these routes in the RouterOutlet of the ParentComponent, not in the RouterOutlet of the AppComponent shell.