Emerceen
Emerceen

Reputation: 2885

Angular2 get active route

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 ?

Upvotes: 3

Views: 4571

Answers (3)

Greg
Greg

Reputation: 1067

With Angular 2 rc4 using router 3.0.0-beta.2 the Directive comment states:

<a routerLinkActive="active" [routerLinkActiveOptions]="{exact: true}" [routerLink]="['/']">HOME</a>

However this also works:

<a [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact: true}" [routerLink]="['/']">HOME</a>

If [routerLinkActiveOptions]="{exact: true}" is omitted the class will not be removed when the route is inactive.

See: https://github.com/angular/angular/blob/master/modules/%40angular/router/src/directives/router_link_active.ts

Upvotes: 1

mihai
mihai

Reputation: 2804

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>

Upvotes: 6

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

Reputation: 657338

You might want to use ActivatedRoute

import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'contacts-detail',
  ...
})
export class ContactsDetailComponent {

  constructor(private route: ActivatedRoute) {

  }
}

Upvotes: 3

Related Questions