Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get active link in Angular 2

Tags:

angular

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?

like image 573
HappyCoder Avatar asked Oct 15 '25 03:10

HappyCoder


1 Answers

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

  • Changing the default name of "router-link-active" class by writing a custom directive that adds new class
  • In Angular 2 how do I assign a custom class to an active router link?

See also

  • Angular: How to determine active route with parameters?

  • In Angular, how do you determine the active route?

  • https://github.com/angular/angular/issues/5334

like image 71
Günter Zöchbauer Avatar answered Oct 17 '25 18:10

Günter Zöchbauer