angular - Angular routerLinkActive 匹配精确路由
问题描述
运行 Angular 8。我的主导航有一组链接,例如/services
. 在那个页面上是服务。但是,当用户单击“生产”时,它会转到 url /services/production
,“服务”导航项会失去其活动状态。
我已申请[routerLinkActiveOptions]="{exact: false}"
尝试在非精确路由上强制执行活动类,但它没有保持活动状态。
这些路由位于它们各自的目录中,因此“服务”有一个services-routing.module
处理它的路由。但是导航链接是根/应用程序级别。
我想我需要将这些路线加载到app-routing.module
但不知道如何去做,如果是这样的话。
尝试延迟加载路由时出现错误:
Error: BrowserModule has already been loaded. If you need access to common directives such as NgIf and NgFor from a lazy loaded module, import CommonModule instead.
我仔细检查并确保我只是在导入BrowserModule
和BrowserAnimationsModule
在app.module
级别。
- - 编辑
我有路由延迟加载,但这并没有解决它。/services
显示活跃但/services/production
不活跃
- - 编辑
应用程序路由模块:
const routes: Routes = [
{ path: 'logout', component: LogoutComponent },
{ path: 'access-denied', component: AccessDeinedComponent }
];
应用程序组件
this.navLinks = [
{ path: '/about', label: 'About', icon: 'assessment' },
{ path: '/contact', label: 'Contact', icon: 'assignment' },
{ path: '/services', label: 'Services', icon: 'settings' }
];
app.component.html
<nav class="nav-tab-group" mat-tab-nav-bar color="accent">
<a mat-tab-link *ngFor="let link of navLinks"
[routerLink]="link.path"
routerLinkActive="mat-tab-label-active active-link"
class="subnav-link">
<mat-icon class="tab-icon">{{link.icon}} is view</mat-icon>
<span class="link-text" >{{link.label}}</span>
</a>
</nav>
services-routing.module(在不同的目录中)
const routes: Routes = [
{
path: '',
component: ServicesComponent,
canActivate: [AuthGuardService],
data: { roles },
children: [
{
path: 'services/production',
component: ProductionComponent,
canActivate: [AuthGuardService],
data: { roles }
}...
]
}
];
因此,services-routing.module 和根 app.component 脚本中的 nav 中的实际路由行为。当我在服务根目录时,服务routerLink
处于活动状态,但所有子项都处于非活动状态。
解决方案
我找到的解决方案是有条件地添加我的活动链接类:
[ngClass]="{'active-link': setActiveNav(link)}"
我的navLinks
变量有一个附加string[]
项,它包含其他可接受的路径,例如['/services/production']
.
返回 true 的方法会查找是否存在其他路径,并在location.path()
使用来自 的 Location 类时检查它是否存在@angular/common
。它还检查预期的路径。
我还有一种情况,导航项需要在完全不相关的 URL 上“活动”。
setActiveNav(navLink): boolean {
const currentPath = this.location.path();
let foundPath = false;
if (navLink.additionalPaths) {
navLink.additionalPaths.forEach(path => {
if (currentPath.indexOf(path) >= 0 || currentPath.indexOf(navLink.path) >= 0) {
foundPath = true;
}
});
} else if (currentPath.indexOf(navLink.path) >= 0) {
foundPath = true;
}
return foundPath;
}
推荐阅读
- java - 将文本文件读入 ArrayList 的 Java 问题
- laravel - Laravel 5.6 Blade Page Loading Spinner
- javascript - 如何通过数字获取变量javascript
- c++ - 为多平台和易于使用的项目组织文件
- javascript - 如何将一个数组的值分配给另一个数组?
- java - 在没有@Autowire 的情况下实例化 Java Spring 存储库接口
- javascript - 如何只导入一次 babel-polyfill
- javascript - 从前端编辑用户信息
- hadoop - 当mapreduce.framework.name设置为local时,如何通过yarn提交mapreduce作业时添加链接第三方库?
- netsuite - 如何从 SuiteTalk 中的客户记录初始化案例记录?