Angular - Lazy loading a module inside module with a child route

倖福魔咒の 提交于 2019-12-05 14:33:04

Since you want a new component to be loaded in case of a child route change and load it as a part of a lazy-loaded module, you can add a <router-outlet></router-outlet> to the template of the user-detail.component.html.

Something like this:

<h1>User Detail</h1>
<ul class="nav">
  <li class="nav-item">
    <a [routerLink]="['/users', user_id, 'user-albums']">User Albums</a>
  </li>
  <li class="nav-item">
    <a [routerLink]="['/users', user_id, 'user-favourites']">User Favourites</a>
  </li>
  <li class="nav-item">
    <a [routerLink]="['/users', user_id, 'user-stats']">User Stats</a>
  </li>
</ul>
<router-outlet></router-outlet>

Now, in the module of this file, define a route configuration to load the respective modules lazily:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';

import { UserDetailComponent } from './user-detail.component';

const routes: Routes = [
  { 
    path: '', 
    component: UserDetailComponent,
    children: [
      {
        path: 'user-albums',
        loadChildren: './user-albums/user-albums.module#UserAlbumsModule'
      },
      {
        path: 'user-favourites',
        loadChildren: './user-favourites/user-favourites.module#UserFavouritesModule'
      },
      {
        path: 'user-stats',
        loadChildren: './user-stats/user-stats.module#UserStatsModule'
      },
    ]
  }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [UserDetailComponent]
})
export class UserDetailModule { }

And then define the lazy modules with their configuration like this:

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';

import { UserAlbumsComponent } from './user-albums.component';

const routes: Routes = [
  { path: '**', component: UserAlbumsComponent }
];

@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes)
  ],
  declarations: [UserAlbumsComponent]
})
export class UserAlbumsModule { }

PS: Since there are a lot of components, I'd suggest that you have a look at the solution stackblitz carefully in order to understand how the routing is wired in.


Here's a Working Sample StackBlitz for your ref.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!