Angular如何添加顶级router-outlet实现独立页面路由切换
实现方法
完全可以通过分层路由搭配独立布局组件实现需求,操作步骤如下:
- 抽离公共布局
新建一个主布局组件(比如命名为MainLayoutComponent),把你当前写在app.component.html里的带顶栏、侧边栏的公共布局代码全部移到这个组件的模板中:
<!-- main-layout.component.html --> <div class="top-half"> <app-top-bar></app-top-bar> </div> <div class="bottom-half"> <app-sidebar></app-sidebar> <router-outlet></router-outlet> </div>
- 简化根组件模板
把app.component.html里原有布局代码全部删除,只保留最顶层的路由出口:
<!-- app.component.html --> <router-outlet></router-outlet>
- 重构路由配置
将需要加载公共布局的业务页面作为主布局组件的子路由,不需要公共布局的独立页面(如登录页)和主布局路由平级配置即可,调整后的路由代码参考:
const routes: Routes = [ // 独立页面(无顶栏、侧边栏)直接配置在顶层 { path: 'login', component: LoginComponent }, // 公共布局路由 { path: '', component: MainLayoutComponent, children: [ { path: '', redirectTo: 'boards', pathMatch: 'full' }, { path: 'boards', component: BoardComponent }, { path: 'boards/:boardId', component: BoardComponent }, // 后续所有需要复用顶栏、侧边栏的页面,都添加到该children数组下 ] }, // 可按需配置404兜底路由 { path: '**', redirectTo: 'boards' } ] @NgModule({ imports: [RouterModule.forRoot(routes)], exports: [RouterModule] }) export class AppRoutingModule { }
效果说明
- 访问
/login这类独立页面路径时,框架会直接把对应组件渲染到根组件的顶层<router-outlet>中,不会加载主布局组件,自然不会展示顶栏、侧边栏 - 访问
/boards等业务路径时,会先加载主布局组件,再把匹配到的业务组件渲染到主布局内部的<router-outlet>中,和你之前的页面展示效果完全一致 - 后续如果需要新增其他布局样式(比如全屏展示页、独立打印页),只需要新增对应的布局组件,按照相同逻辑配置平级路由即可,不需要改动现有业务代码
内容的提问来源于stack exchange,提问作者Victor Zlatin
相关产品推荐
相关产品推荐

