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

Angular 11 如何将组件加载到主router-outlet外的嵌套路由出口中

解决方案

问题根因

只有注册为LayoutComponent子路由的路径,才会被加载到Layout组件内部的嵌套<router-outlet>中,没有匹配到嵌套层级的路由会默认使用根组件的主<router-outlet>渲染,因此出现全页替换的情况。

调整步骤

  • 第一步:修改layout.routing.module.ts的路由配置,补充空路径重定向规则,同时将所有需要嵌套在布局内的业务路由全部注册到children数组中:
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

import { LayoutComponent } from './layout.component';
import { HomeComponent } from '@modules/home/home.component';
// 后续引入其他需要嵌套布局的业务组件/懒加载模块

const routes: Routes = [
  {
    path: '', component: LayoutComponent,
    children: [
      // 新增空路径重定向,访问根路径时自动跳转首页,加载到嵌套outlet
      { path: '', redirectTo: 'home', pathMatch: 'full' },
      { path: 'home', component: HomeComponent },
      // 示例:其他业务页面路由,直接注册即可复用布局
      // { path: 'user', component: UserComponent },
      // 示例:懒加载业务子模块,模块内部路由自动继承嵌套层级
      // { path: 'order', loadChildren: () => import('../order/order.module').then(m => m.OrderModule) }
    ]
  }
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class LayoutRoutingModule { }
  • 第二步:校验app-nav-menu组件中的routerLink配置,确保跳转路径和children数组中注册的路径匹配,比如跳转到首页可写为routerLink="/home"。
  • 第三步:后续新增业务页面时,只要是需要带侧边栏、顶部栏的布局页面,全部注册到LayoutComponent的children路由数组中即可,不需要修改根路由配置。

内容的提问来源于stack exchange,提问作者Aldemar Cuartas Carvajal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:06:03