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
相关产品推荐
相关产品推荐

