Home > Enterprise >  How to give routerLinkActive for the same link in different section in Angular?
How to give routerLinkActive for the same link in different section in Angular?

Time:06-29

I have two sections, pinned tools section and all tools section. Both sections contains same routerLink. If I click on the pinned tools section menu routerLink, it should apply routerLinkActive class only that pinned tools section only. But now that routerLinkActive class applied to that both section pinned tools and all tools section.

All Tools section:

<ul  id="parentdrop{{i}}">
            <li  *ngFor="let subitem of item.submenus; let j = index;" id="clickedSubMenu{{j}}" (click)="expandSubMenu($event,j,i)">
              <a [routerLink]="['/app/'   subitem.menu.split(' ').join('').replace('-','')]" [routerLinkActive]="['allToolsActive']" (click)="alltoolsCheckClick(subitem.id, subitem.menu)" id="clickedSMenu{{i}}">{{subitem.menu}}</a>
            </li>

          </ul>

Pinned Tools Section:

 <div id="{{sub.id}}"  [routerLink]="['/app/'   sub.menu.split(' ').join('').replace('-','')]" [routerLinkActive]="['active']" #rla1="routerLinkActive" (click)="pinnCheckClick(sub.id, sub.menu!==' '?sub.menu:sub.category)">

                <span>
                  <img src='{{ "/src/assets/icons/"   sub.category   ".svg" }}'  />


                </span>

                <div >
                  <span >{{sub.category}}</span>
                  <div>{{sub.menu}}</div>
                </div>

              </div>

CodePudding user response:

I suspect you can't do what you likely want to do. The point is that so long as the target route is active, it will give your specified class to the element so that you can style it to your hearts desire.

If both are hooked up to the route, they'll both be active whilst on that route.

The only way round that is to handle things yourself. First thing that comes to mind is to leave the duplicate active stuff in there, and add a new class when you select one of those options.

Then your css can react to whichever of those was actually clicked;

.active.clicked {
    background-color: red;
}
<a ... (click)="onToolsClick()" [class.clicked]="userClickedTools">Tools</a>
<a ... (click)="onPinnedToolsClick()" [class.clicked]="userClickedPinnedTools">Pinned Tools</a>
public onToolsClick(): void {
    this.userClickedTools = true;
    this.userClickedPinnedTools = false;
}

public onPinnedToolsClick(): void {
    this.userClickedTools = false;
    this.userClickedPinnedTools = true;
}

Something like that?

  • Related