3

I am attempting to get the active link in Angular 2 so I can update my css in my template.

This is what I have done with the help of google:

export class AppComponent {
    router: Router;

    constructor(data: Router) {
        this.router = data;
    }

    isActive(tab): boolean {
        if (this.router.currentInstruction && this.router.currentInstruction.component.routeData) {
            return tab == this.router.currentInstruction.component.routeData.data['activeTab'];
        }
        return false;
    }
}

My template is as follows:

  <li class="some-class" [ngClass]="{active: isActive('some-route')}">

                <a [routerLink]="['SomeRoute']" class="menu-item" ><span>Link1</span></a>

            </li>

While this works, I note the RouterLink directive has the method: isRouteActive.

This would seem like a sensible way to manipulate the link class using this.

But how do I use it?

HappyCoder
  • 5,675
  • 6
  • 39
  • 69

1 Answers1

5

Update RC.3:

In RC.3 there was a new directive routerLinkActive added.

routerLinkActive="classA classB class" [routerLinkActiveOptions]="{exact: true}"

Original:

Angular router sets router-link-active class automatically on active router links.

If you want custom classes you can use something like

See also

Ajit Panigrahi
  • 723
  • 11
  • 25
Günter Zöchbauer
  • 558,509
  • 191
  • 1,911
  • 1,506