基于routerLinkActive的角度突出显示

时间:2019-07-07 13:05:43

标签: javascript css angular

我想根据路线切换routerLinkActive的高亮显示, 我有一个仪表板组件,并且仪表板菜单项和标签菜单项都引用相同的组件,我想根据路线将类添加到li项中 对于仪表板,路线将为

http://localhost:4300/dashboard

对于标签,路线将为

http://localhost:4300/dashboard/5d1bb53877ed8702d8a01940

菜单项的代码

 <ul class="sidebar-nav">
                <li [ngClass]="{ active: rlal && rlal.isActive == false }">
                  <a [routerLink]="['/dashboard']" (click)="loadSnippet(null)">
                    <mat-icon>dashboard</mat-icon>
                    <span>Dashboard</span>
                  </a>
                </li>

     <h3 *ngIf="labelList && labelList.length!=0">Labels</h3>
              <ul class="sidebar-nav">
                <li *ngFor="let label of labelList" [ngClass]="rlal && rlal.isActive ? 'active' : ''"
                  routerLinkActive="rlal.isActive">
                  <a [routerLink]="['/dashboard', label._id]" routerLinkActive #rlal="routerLinkActive"
                    (click)="loadSnippet(label)">
                    <mat-icon>label</mat-icon>
                    <span>{{ label.label_name }} </span>
                  </a>
                </li>
              </ul>

路线:

 {
    path: "dashboard",
    component: DashboardComponent,
    canActivate: [LoggedInGuard]
  },
  {
    path: "dashboard/:labelId",
    component: DashboardComponent,
    canActivate: [LoggedInGuard]
  }

突出显示对单个标签项目效果很好,但是对于仪表板,li不会突出显示

enter image description here

1 个答案:

答案 0 :(得分:1)

如果仅在没有路由参数的情况下才希望仪表板链接处于活动状态,则需要向仪表板routerLinkActive节点添加[routerLinkActiveOptions]="{exact: true}"li

此外,您无需通过active来设置ngClass类,因为routerLinkActive会为您完成此操作。

<li routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}">
  <a routerLink="/dashboard" (click)="loadSnippet(null)">
    <mat-icon>dashboard</mat-icon>
    <span>Dashboard</span>
  </a>
</li>

 ...

<li routerLinkActive="active" *ngFor="let label of labelList">
  <a [routerLink]="['/dashboard', label._id]" (click)="loadSnippet(label)">
    <mat-icon>label</mat-icon>
    <span>{{ label.label_name }}</span>
  </a>
</li>