Angular routerLinkActive正在匹配确切的路由

时间:2020-04-16 23:32:44

标签: angular angular2-routing

运行Angular 8.我的主导航有一组链接,例如/services。在该页面上是服务。当用户单击“生产”时,它会转到URL /services/production,“服务”导航项将失去其活动状态。

我已经应用[routerLinkActiveOptions]="{exact: false}"来尝试在非精确路由上强制使用活动类,但是它并没有保持活动状态。

这些路由位于各自的目录中,因此“服务”具有services-routing.module来处理其路由。但是,导航链接是root / app级别。

我认为我需要将这些路由加载到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级别导入BrowserAnimationsModuleapp.module

---编辑

我有延迟加载的路由,但无法解决。 /services显示为活动状态,但/services/production未显示

---编辑

app-routing.module:

const routes: Routes = [
  { path: 'logout', component: LogoutComponent },
  { path: 'access-denied', component: AccessDeinedComponent }
];

app.component

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中的实际路由行为以及root app.component脚本中的nav。当我在服务根目录时,服务routerLink处于活动状态,但所有子级均处于非活动状态。

1 个答案:

答案 0 :(得分:0)

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

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