Search code examples
angularangular-material

How to add lazily loaded modules in angular inside mat sidenav content?


In angular app how to add lazily loaded modules/rotes inside mat sidenav content?


Solution

  • You can use angular-modules for your sidenav content which can be easil lazy loaded and each module can have its own path/paths.

    Sample execution might look like this:

    // app-routing.module.ts
    const routes: Routes = [
      {
        path: '',
        component: MainLayoutComponent,
        children: [
          {
            path: 'module1',
            loadChildren: () => import('./module1/module1.module').then(m => m.Module1Module)
          },
          {
            path: 'module2',
            loadChildren: () => import('./module2/module2.module').then(m => m.Module2Module)
          }
          // Add more lazy-loaded modules as needed
        ]
      }
    ];
    

    Then in the HTML, you can load these routes:

    <!-- main-layout.component.html -->
    <mat-sidenav-container>
      <mat-sidenav mode="side" opened>
        <!-- Sidenav content -->
        <mat-nav-list>
          <a mat-list-item routerLink="/module1">Module 1</a>
          <a mat-list-item routerLink="/module2">Module 2</a>
        </mat-nav-list>
      </mat-sidenav>
      
      <mat-sidenav-content>
        <!-- This is where your lazy-loaded content will appear -->
        <router-outlet></router-outlet>
      </mat-sidenav-content>
    </mat-sidenav-container>
    

    Your each module might be different and can have different routes and those can be defined in your module's each routing section. Like this:

    // module1.module.ts
    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import { RouterModule, Routes } from '@angular/router';
    import { Module1Component } from './module1.component';
    
    const routes: Routes = [
      { path: '', component: Module1Component }
    ];
    
    @NgModule({
      declarations: [Module1Component],
      imports: [
        CommonModule,
        RouterModule.forChild(routes)
      ]
    })
    export class Module1Module { }
    

    Just be sure that you are loading the right modules in the right section and this should work.