首页 > 解决方案 > 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.

我仔细检查并确保我只是在导入BrowserModuleBrowserAnimationsModuleapp.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处于活动状态,但所有子项都处于非活动状态。

标签: angularangular2-routing

解决方案


我找到的解决方案是有条件地添加我的活动链接类:

[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;
  }

推荐阅读