HappyCoder
HappyCoder

Reputation: 6155

Get active link in Angular 2

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?

Upvotes: 3

Views: 1726

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657108

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

Upvotes: 5

Related Questions