You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Angular的Mat Sidenav内容区域中添加懒加载模块/路由?

在Angular中将懒加载模块/路由添加至Mat Sidenav内容区域的方法

1. 配置懒加载路由

先通过Angular CLI生成带路由的懒加载模块(以dashboard模块为例):

ng generate module dashboard --route dashboard --module app.module

该命令会自动在app-routing.module.ts中添加懒加载路由配置,也可以手动编写:

// app-routing.module.ts
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
  // 其他基础路由
  {
    path: 'dashboard',
    loadChildren: () => import('./dashboard/dashboard.module').then(m => m.DashboardModule)
  },
  {
    path: 'settings',
    loadChildren: () => import('./settings/settings.module').then(m => m.SettingsModule)
  }
];

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

每个懒加载模块内部需配置子路由,比如dashboard-routing.module.ts:

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { DashboardComponent } from './dashboard.component';

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

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

2. 搭建Mat Sidenav布局

在主组件模板(如app.component.html)中设置Mat Sidenav结构,将<router-outlet>放入mat-sidenav-content内部,懒加载组件会自动渲染到这个区域:

<mat-sidenav-container class="sidenav-container">
  <mat-sidenav #sidenav mode="side" opened>
    <!-- 侧边栏导航链接 -->
    <mat-nav-list>
      <a mat-list-item [routerLink]="['/dashboard']" routerLinkActive="active-link">
        <mat-icon>dashboard</mat-icon>
        <span>Dashboard</span>
      </a>
      <a mat-list-item [routerLink]="['/settings']" routerLinkActive="active-link">
        <mat-icon>settings</mat-icon>
        <span>设置</span>
      </a>
    </mat-nav-list>
  </mat-sidenav>
  <mat-sidenav-content>
    <!-- 懒加载组件渲染位置 -->
    <router-outlet></router-outlet>
  </mat-sidenav-content>
</mat-sidenav-container>

3. 路由激活样式配置(可选)

为当前激活的侧边栏链接添加高亮效果,在app.component.css中编写:

.active-link {
  background-color: rgba(0, 0, 0, 0.1);
}

核心要点

  • mat-sidenav-content是Mat Sidenav的内容容器,<router-outlet>放置在此后,路由切换时懒加载组件会自动填充到该区域。
  • routerLink需与懒加载路由的路径完全匹配,routerLinkActive会自动为当前激活的路由链接绑定指定样式。
  • 每个懒加载模块必须通过RouterModule.forChild()配置子路由,确保模块内的组件能被正确路由到。

内容的提问来源于stack exchange,提问作者Alok Agase

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 11:32:36