3

In my app there is more than one way to route to a particular resource, for example, I got breadcrumbs in order to be able to navigate more freely through a hierarchy of items

SectionA > SectionB > SectionC

where SectionA has id=1 and so on. At the same time I got a routerLink in my side menu to the currently selected item, which in the above example would point to SectionC (id=3). I keep these synchronous by emitting an event when someone clicks on a breadcrumb and then binding the id from the event to the routerLink in my side menu:

<li>
    <a [routerLink]="['/section, section? section.id : 0]" [routerLinkActive]="['active']"></a>
</li>

This way, if the user navigates away from that component they can come back to the same state by just clicking on the button in the side menu (instead of having to navigate to their target section from scratch).

This does actually work fine, however, if I navigate through the breadcrumbs (and thus am using the binding to section from above) routerLinkActive doesn't fire although the current URL and the URL on the side menu button are identical.

Only if I click the side menu button directly is the active class applied, it doesn't work through the binding.

It works for URLs without parameters (no binding there), so I guess it's to do with Angular's change checking.

Question is, is this intended behaviour and if so, what am I supposed to do in order to get this to work anyway?

Thorsten Westheider
  • 10,572
  • 14
  • 55
  • 97

2 Answers2

4

Copied this question and marked as wiki since I'm not trying to gain karma: https://stackoverflow.com/a/40528170/88066

1) in your component

import {Router} from 'angular2/router';

isActive(instruction: any[]): boolean {
    return this.router.isActive(this.router.createUrlTree(instruction), true);
}

2) in your html

<a [class.active]="isActive(['user', currentUser.name])">

Router docs on angular.io

Community
  • 1
  • 1
Tim Coker
  • 6,484
  • 2
  • 31
  • 62
-2

It should be

  <a [routerLink]="['/inbox']" class="link" routerLinkActive="active">Inbox</a>

Because it's a directive

 ROUTER_DIRECTIVES = [RouterOutlet, RouterLink, RouterLinkActive];

Also consider specifying a routerLinkActiveOptions if it is the case:

<a [routerLinkActiveOptions]="{exact: exact}" ...

null canvas
  • 10,201
  • 2
  • 15
  • 18