Angular路由跳转异常 点击CRUD/PIPES按钮仍显示首页表格
问题相关参考截图
问题根因
Angular中<router-outlet>是路由组件的唯一渲染出口,根组件AppComponent本身是全局常驻组件,模板里写在<router-outlet>标签外的所有内容,会在所有路由页面固定显示,不会随路由切换消失。
你当前把员工表格的全部代码直接写在了app.component.html的<router-outlet>之前,因此无论切换到哪个路由,员工表格都会保留在页面上,路由匹配到的CrudComponent/PipesComponent内容只会被渲染到<router-outlet>位置,也就是表格下方,和你遇到的现象完全一致。
修复方案
按照Angular路由的设计规范,每个独立页面的内容都应该放在独立的组件中,由路由控制渲染,不要把单页内容直接写在根组件里,按以下步骤修改即可:
- 生成独立的首页组件承载员工表格功能,在项目目录执行命令:
ng generate component home - 把
app.component.html中整块员工表格代码(即从<div class="container">开始到对应闭合</div>的所有表格相关模板),全部剪切到新生成的home.component.html中。同时把app.component.ts里和员工表格相关的逻辑(包括openDialog、editEmployee、deleteEmployee方法,dataSource、displayedColumns属性,以及依赖注入的MatDialog、数据服务等)全部迁移到home.component.ts中,补全HomeComponent需要的模块导入。 - 修改路由配置,打开
app-routing.module.ts,更新路由数组,给根路径绑定首页组件:
const routes: Routes = [ {path:'', component: HomeComponent}, // 根路径默认渲染员工表格首页 {path:'crud', component: CrudComponent}, {path:'pipes', component: PipesComponent} ];
- 精简根组件模板,打开
app.component.html,删除所有员工表格相关代码,只保留全局工具栏和路由出口,建议给路由链接加上前导斜杠使用绝对路径,避免嵌套路由异常,最终代码如下:
<mat-toolbar color="primary" class="mat-elevation-z6"> <button mat-icon-button class="example-icon" aria-label="Example icon-button with menu icon"> <mat-icon>group_work</mat-icon> </button> <span> ANGULAR </span> <div class="spacer"></div> <a mat-button routerLink="/" routerLinkActive="active"> 员工列表 </a> <a mat-button routerLink="/crud" routerLinkActive="active"> CRUD </a> <a mat-button routerLink="/pipes" routerLinkActive="active"> PIPES </a> </mat-toolbar> <router-outlet></router-outlet>
- 打开
app.module.ts,在declarations数组中加入新建的HomeComponent,确保组件被正确声明。
修改完成后,路由切换时<router-outlet>会完全替换渲染的组件内容:访问根路径显示员工表格,点击CRUD/PIPES按钮时表格会消失,仅显示对应路由页面的内容,符合预期。
内容的提问来源于stack exchange,提问作者Maryam Faheem
相关产品推荐
相关产品推荐

