Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 get active route

Tags:

angular

routes

After update to Angular2 rc2, and Angular2 rc3, I have error

"Property 'urlTree' does not exist on type 'Router'"

My function

isRouteActive(routePath) {
    return this.router.urlTree.contains(this.router.createUrlTree(routePath));
}

How to get active link in angular2 rc3 ?

like image 395
Emerceen Avatar asked Oct 19 '25 11:10

Emerceen


1 Answers

If you are going to style some element according to activeRoute you can use the directive [routerLinkActive]="['your-class-name']" to the element.

routerLinkActive directive source


UPDATE

Old style (with router-deprecated):
html layout

<li [class.active]="isActive(['Dashboard'])">
    <a [routerLink]="['dashboard']"><span class="nav-label">Dashboard</span></a>
</li>

*.ts component

isActive(instruction: any[]): boolean {
    return this.router.isRouteActive(this.router.generate(instruction));
}

New style (with router version 3.0.0-alpha.7):
only html layout needed

<li [routerLinkActive]="['active']">
    <a [routerLink]="['dashboard']"><span class="nav-label">Dashboard</span></a>
</li>
like image 187
mihai Avatar answered Oct 22 '25 00:10

mihai



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!