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

Angular中如何根据路由链接切换显示不同Div?

根据当前路由切换显示Div的实现方案

步骤1:在组件类中注入Router服务

先在组件的TypeScript文件(component.ts)里导入并注入Angular的Router服务,用来获取当前路由信息:

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

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

步骤2:在模板中添加路由判断逻辑

修改你的component.html,用*ngIf指令结合router.url,根据当前路由显示对应的Div:

<div class="div-one" *ngIf="router.url === '/profile/add'">
  <!-- div-one的内容 -->
</div>

<div class="div-two" *ngIf="router.url === '/user/info'">
  <!-- div-two的内容 -->
</div>

补充说明

  • 要确保项目已经正确配置Angular路由模块,且/profile/add和/user/info这两个路由已经在路由配置中注册。
  • 如果需要匹配带参数的路由(比如/profile/add/:id),可以用router.url.includes('/profile/add')做模糊匹配,或者通过ActivatedRoute获取路由参数做更精准的判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:20:23