Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to lazy load a route as a child route/component

Let's take a look at my plunker: https://plnkr.co/edit/22RIoGsvzfw2y2ZTnazg?p=preview

I want to lazy load a Module as a child-route.

So the route /lazy should render the LazyModule into the <router-outlet> of my MainComponent.

Then it will switch between that DummyComponent and the lazy loaded Module.

Instead now that lazy loaded Module will be rendered into the AppComponent..

Any ideas?

like image 242
slaesh Avatar asked Nov 25 '16 07:11

slaesh


1 Answers

If you want to lazy load a module, do not import it as you've done here :

src/app.ts :

import { LazyModule } from './lazy/lazy.module';
...

@NgModule({
  imports: [ BrowserModule, RouterModule.forRoot(routes), LazyModule ]

If you load a module (using import) it will be bundled into the main module instead of having a separated chunk.

Replace it by :

@NgModule({
  imports: [ BrowserModule, RouterModule.forRoot(routes) ]

Then your routes should be like that :

const routes = [
  {
    path: '',
    component: MainComponent,
    children: [
      {
        path: '',
        component: DummyComponent
      },
      // should be rendered as a CHILD of my MainComponent .. !!
      {
        path: 'lazy',
        loadChildren: 'src/lazy/lazy.module#LazyModule'
      }
    ]
  }
];

Notice that loadChildren path starts from src now.


For src/lazy/lazy.module.ts : You should have your routes defined (as it's needed for children modules) BUT your routes should be empty because they'll be suffixed by their parent's routes. (here : '/lazy').

So if you put :

const routes = [
  {
    path: 'lazy',
    component: LazyComponent
  }
];

You expect to match /lazy/lazy to use your lazy component, which is not what you want.

Instead use :

const routes = [
  {
    path: '',
    component: LazyComponent
  }
]

Here's the working Plunkr : https://plnkr.co/edit/KdqKLokuAXcp5qecLslH?p=preview

like image 101
maxime1992 Avatar answered Oct 25 '22 23:10

maxime1992