为活动路由器链接的父级Angular 2+设置一个类

时间:2019-02-04 14:48:45

标签: angular css3

我有一个带有下拉菜单的bootstrap 4导航栏,该下拉菜单包含路由,我可以基于“ routerLinkActive”使它们显示为活动状态,但我也想设置“ dropdown-toggle”或“ nav-item”的样式当其子级之一为活动路线时,则为活动状态。

我该怎么做?

这是代码的一小段,我已尝试对其进行清理以使其易于阅读

<li *ngFor="let menuItem of MenuItems; index as i" [id]="i" class="nav-item dropdown" ngbDropdown>

  <a class="nav-link dropdown-toggle" ngbDropdownToggle>
    {{menuItem.title}}
  </a>

  <!-- dropdown menu -->
  <div *ngIf="menuItem.submenu.length > 0" class="dropdown-menu" ngbDropdownMenu aria-labelledby="i">
    <div *ngFor="let menuSubItem of menuItem.submenu">
        <a  [routerLink]="menuSubItem.path"
            [routerLinkActive]="['active-sub']" <== ** this part works and sets the class, now i need the top nav-link to be active too
            [routerLinkActiveOptions]="{exact: true}" 
            class="dropdown-item">
            {{menuSubItem.title}}
        </a>
    </div>
  </div>

</li>

2 个答案:

答案 0 :(得分:0)

您可以像这样使用routerLinkActive模板引用:

<li [ngClass]="{'active-class': rlRef.isActive}">
  <a [routerLink]="['/your-route']" routerLinkActive="active" #rlRef="routerLinkActive">Fancy URL</a>
<li>

答案 1 :(得分:0)

我找到了一个非常笨拙的解决方案,类似于先前的解决方案。它还利用导出routerLinkActive作为模板变量,然后使用组件中的@ViewChildren捕获导出变量的实例。因此,HTML将具有:

<li *ngFor="let menuItem of MenuItems; index as i" [id]="i" class="nav-item dropdown" [ngClass]="active: getRLA" ngbDropdown>

  <a class="nav-link dropdown-toggle" ngbDropdownToggle>
    {{menuItem.title}}
  </a>

  <!-- dropdown menu -->
  <div *ngIf="menuItem.submenu.length > 0" class="dropdown-menu" ngbDropdownMenu aria-labelledby="i">
    <div *ngFor="let menuSubItem of menuItem.submenu">
        <a  [routerLink]="menuSubItem.path"
            [routerLinkActive]="['active-sub']" <== ** this part works and sets the class, now i need the top nav-link to be active too
            [routerLinkActiveOptions]="{exact: true}"
            #rla="routerLinkActive"
            class="dropdown-item">
            {{menuSubItem.title}}
        </a>
    </div>
  </div>

</li>

然后在Component中,您可以获取模板变量并解析任何活动的RouterLinkActive对象:

@ViewChildren('rla') routerLinkActiveReferences: QueryList<RouterLinkActive>;

get getRLA() {
    return !!this.routerLinkActiveReferences.find(rla => rla.isActive === true);
}