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

如何在Angular中根据路由链接控制Div的显示?

Angular 根据路由控制组件内Div的显示

第一步:在组件类中获取当前路由信息

在filter.component.ts中注入Router,通过它获取当前激活的路由路径:

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
  selector: 'app-filter',
  templateUrl: './filter.component.html',
  styleUrls: ['./filter.component.css']
})
export class FilterComponent {
  constructor(private router: Router) {}

  // 获取当前路由的完整路径
  get currentRoute(): string {
    return this.router.url;
  }
}

第二步:修改模板文件控制Div显示

在filter.component.html中,使用*ngIf指令根据当前路由判断显示对应的Div:

<!-- Div 1:仅在/contact页面显示 -->
<div *ngIf="currentRoute === '/contact'">
  <!-- 这里放Div 1的内容 -->
</div>

<!-- Div 2:仅在/profile或/about页面显示 -->
<div *ngIf="currentRoute === '/profile' || currentRoute === '/about'">
  <!-- 这里放Div 2的内容 -->
</div>

补充说明

如果你的路由带有参数(比如/profile/123),可以用包含判断来适配参数场景,避免参数影响匹配结果:

<div *ngIf="currentRoute.includes('/profile') || currentRoute.includes('/about')">
  <!-- Div 2内容 -->
</div>

内容的提问来源于stack exchange,提问作者user19610519

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:35:36