在Angular中,要实现两个不同路径下的相同菜单项处于活动状态,可以使用ActivatedRoute的属性来判断当前路由是否与菜单项的路径相匹配,并在模板中设置相应的CSS类来表示活动状态。
以下是一个示例代码:
首先,在菜单组件中,定义一个菜单项的数组,并使用ngFor指令生成菜单项:
-
{{ item.label }}
在组件的类中,定义菜单项的数组和当前路由路径的变量,并注入ActivatedRoute服务:
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-menu',
templateUrl: './menu.component.html',
styleUrls: ['./menu.component.css']
})
export class MenuComponent {
menuItems = [
{ label: 'Home', path: '/home' },
{ label: 'About', path: '/about' },
{ label: 'Contact', path: '/contact' }
];
currentPath: string;
constructor(private route: ActivatedRoute) {
this.route.url.subscribe(url => {
this.currentPath = url.join('/');
});
}
isActive(path: string) {
return this.currentPath === path;
}
}
在isActive方法中,判断当前路由路径是否与菜单项的路径相匹配,如果相同,则返回true,表示活动状态。
最后,在菜单组件的CSS文件中,定义活动状态的样式:
.active {
background-color: #ccc;
}
这样,当路由路径与菜单项的路径匹配时,相应的菜单项会被设置为活动状态,应用了活动状态的CSS样式。