Eugene
Eugene

Reputation: 3957

Angular - detect active route in ngIf

I want to display a different markup for active and inactive menu items so that active menu item doesn't include a tag:

<li>
    <a routerLink="/abc">Inactive</a>
</li>    
<li>Active</li>

The routerLinkActive directive doesn't help here since it can only add some class for active route but not to use a different markup. I understand that I can inject Router to my component and use something like this

<li>
    <ng-container *ngIf="router.isActive('/abc')">Active</ng-container>
    <a *ngIf="!router.isActive('/abc')" routerLink="/abc">Inactive</a>
</li>

but is there a better built-in solution for this case?

Upvotes: 4

Views: 6255

Answers (1)

Zze
Zze

Reputation: 18805

The routerLinkActive directive doesn't help here since it can only add some class for active route but not to use a different markup.

Well actually...

<input type="hidden" [routerLink]="'home'" routerLinkActive #home="routerLinkActive" />
<section *ngIf="home.isActive"></section>

The routerLinkActive variable is bound to a template variable and then re-used as required. Unfortunately the only caveat is that you can't have this all on the <section> element as #home needs to be resolved prior to the parser hitting <section>.

Upvotes: 7

Related Questions