Search code examples
angularlazy-loadingdynamic-feature-module

Lazy-loading in feature modules- Angular


The app stays here: https://angular-dqpbqa.stackblitz.io. what mistake am i doing? and it also loads heroes-list initially, but the path is ''.

lazyloading of feature modules is not working. i have created separate routing in each feature module. dynamically loading the module using loadchildren property

const routes: Routes = [
{ path: 'dashboard',
  loadChildren: () => import('./dashboard/dashboard.module').then(mod => 
mod.DashboardModule)
},
 { path: 'heroes',
  loadChildren: () => import('./heroes/heroes.module').then(mod => 
mod.HeroesModule)
},
{ path: 'detail/:id',
  loadChildren: () => import('./hero-detail/hero-detail.module').then(mod 
=> mod.HeroDetailModule)
},
{
path: '',
redirectTo: '',
pathMatch: 'full'
},

];

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

stackblitz-editable: https://stackblitz.com/edit/angular-dqpbqa


Solution

  • HeroesModule is not lazy-loaded because it is imported in app.module.ts <= that's the mistake

    @NgModule({
      imports: [ /* ... */ HeroesModule, /* ... */ ]
    })
    export class AppModule { }
    

    There, HeroesModule is initially loaded and the app has access to the routes of heroes-routing.module.ts

    So when you navigate to '', the path will match the path '' defined in your heroes-routing.module.ts which display the HeroesComponent