如何在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
相关产品推荐
相关产品推荐

