Angular8中如何根据routerLinks实现指定元素的显隐控制?
Angular 8 按路由控制盒子显隐实现方案
方案1:直接匹配路由路径(简单场景首选)
适合路由路径固定、无复杂嵌套的场景
- 组件TS中注入Router并定义匹配规则
// 顶部导入依赖 import { Router } from '@angular/router'; export class YourComponent { // 填入需要显示box-A的3个路由路径 readonly showBoxARoutes = ['/route1', '/route2', '/route3']; constructor(public router: Router) {} }
- 模板中添加判断条件
<!-- 仅匹配到指定路由时显示box-A --> <div class="box-A" *ngIf="showBoxARoutes.includes(router.url)">box-A 内容</div> <!-- 其余路由显示box-B --> <div class="box-B" *ngIf="!showBoxARoutes.includes(router.url)">box-B 内容</div>
方案2:路由配置加标记(可维护性更高)
适合后续可能新增路由、路由嵌套复杂的场景
- 路由配置文件中给每个路由增加自定义标记
const routes: Routes = [ // 需显示box-A的3个路由,添加data标记 { path: 'route1', component: Cmp1, data: { showBox: 'A' } }, { path: 'route2', component: Cmp2, data: { showBox: 'A' } }, { path: 'route3', component: Cmp3, data: { showBox: 'A' } }, // 需显示box-B的3个路由,添加对应标记 { path: 'route4', component: Cmp4, data: { showBox: 'B' } }, { path: 'route5', component: Cmp5, data: { showBox: 'B' } }, { path: 'route6', component: Cmp6, data: { showBox: 'B' } }, ]
- 组件TS中监听路由获取标记
import { ActivatedRoute, NavigationEnd, Router } from '@angular/router'; export class YourComponent { currentShowBox: 'A' | 'B' = 'A'; constructor( private router: Router, private activatedRoute: ActivatedRoute ) {} ngOnInit() { // 监听路由切换事件,实时更新显示标记 this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { this.currentShowBox = this.activatedRoute.snapshot.firstChild?.data?.showBox || 'A'; } }) } }
- 模板中按标记判断显隐
<div class="box-A" *ngIf="currentShowBox === 'A'">box-A 内容</div> <div class="box-B" *ngIf="currentShowBox === 'B'">box-B 内容</div>
注意事项
- 如果路由带查询参数/hash,可使用
this.router.parseUrl(this.router.url).path获取纯路径再做匹配 - 如需模糊匹配父路由下所有子路由,可使用Angular内置方法
router.isActive('/parent-route', false),第二个参数传false为模糊匹配,传true为精确匹配
内容的提问来源于stack exchange,提问作者Amol
相关产品推荐
相关产品推荐

