0
votes

I have a bootstrap 4 navbar with a dropdown, the dropdown contains the routes and I can get those to appear active based on the 'routerLinkActive' but I also want to style the 'dropdown-toggle' or 'nav-item' as active when one of its children is the active route.

How would i go about doing this ?

Here is a small snippet of the code, I have tried to clean it up for ease of reading

<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
stackoverflow.com/help/how-to-ask - provide an example of what you have tried and read the guidelines for asking please.nstanard

2 Answers

2
votes

You can use routerLinkActive template reference like this:

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

I found a very hacky solution to this similar to a previous one. It also utilizes exporting routerLinkActive as a template variable and then grabbing instances of the exported variable using @ViewChildren in the component. So the HTML will have:

<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>

And then in the Component, you can grab the template variable and parse for any active RouterLinkActive objects:

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

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