Aico Klein Ovink
Aico Klein Ovink

Reputation: 1647

Angular: How to determine active route with parameters?

I've read this question about how to determine the active route, but still it's not clear to me how to determine an active route with paramaters?

Right now I'm doing it like this:

<a [routerLink]="['/Profile/Feed', {username: username}]"
   [ngClass]="{active: getLinkStyle('/profile/john_doe/feed')}">
   Feed for {{username}}
</a>

And inside my component:

getLinkStyle(path:string):boolean {
  console.log(this._location.path()); // logs: '/profile/john_doe/feed'
  return this._location.path() === path;
}

And this will work because I'm passing the username as a string. Is there any way to do this with passing the correct parameter??

Upvotes: 16

Views: 28001

Answers (8)

Ayesha
Ayesha

Reputation: 311

<a [routerLink]="['/Profile/Feed', {username: username}]"
routerLinkActive="active-item" [routerLinkActiveOptions]="{exact: false}">
   Feed for {{username}}
</a>

active-item is your css class which you want to give for active menu. routerLinkActive is used for giving css for active menu, where as routerLinkActiveOptions will tell you whether you want the url to be matched exactly. this usually helps in where you have same url for create and edit (with param)

example:

for create:

http://localhost/feed

for edit:

http://localhost/feed/1

Upvotes: 0

VISHNU
VISHNU

Reputation: 966

try this :

<li   class="ann_profileimg" [routerLinkActive]="['active']" [routerLink]="['profile']">
            <div class="ann_header_menu_left ann_profile_avatar_small"></div>
            <span>Vishnu </span>
          </li>

Upvotes: 1

asmmahmud
asmmahmud

Reputation: 5044

For Angular version 4+, determining a active route in the template is fairly easy as there is a build-in directive for this purpose name routerLinkActive which you can use the following way:

      <li class="nav-item" routerLinkActive="active">
        <a class="nav-link" routerLink="/home">Home</a>
      </li>
      <li class="nav-item" routerLinkActive="active">
        <a class="nav-link" routerLink="/about-us">About Us</a>
      </li>
      <li class="nav-item" routerLinkActive="active">
        <a title="Contact Us" class="nav-link " routerLink="/contact-us">Contact</a>
      </li>
    </ul>

Upvotes: 0

Michael Oryl
Michael Oryl

Reputation: 21642

With the new, up and coming Angular 2 router (at version 3.0-alpha.7 as I write this), it's very simple.

All you need to do is use the [routerLinkActive] directive in your link.

<a [routerLinkActive]="['active']" [routerLink]="['/contact',  contact.id ]">
    {{contact.name}}
</a>

This is what you will be using when Angular 2 is released for real, and no longer a release candidate. I'm using the alpha of the router now and not having any issues.

Here's Plunk demonstrating it. You can see that the links go red as you click on them. That's the directive assigning the active class to them. You could use any class name of your choosing, of course.

Upvotes: 19

Brian
Brian

Reputation: 5028

You can use new Location service from Angular2 common package: https://angular.io/docs/js/latest/api/router/Location-class.html#!#path-anchor

import { Location } from '@angular/common';

...

export class YourClass {
    constructor(private _loc:Location) {}

    getCurrentPath() {
        return this._loc.path();
    }
}

Note: it's better to use Router service to trigger route changes. Use Location only if you need to interact with or create normalized URLs outside of routing.

Please note: Documentation says import from router, but the latest betta version I have has Location services in common.

Upvotes: 1

Mcanic
Mcanic

Reputation: 1393

In Angular 2 rc1 router.isRouteActive does not exist anymore. I could not find a working solution anywhere, but I was able to solve it like this (the custom method isActiveRoute does the trick):

App.component.ts:

import { Component } from '@angular/core';
import { Routes, Route, Router, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router';
import { HomeComponent } from './home.component';
import { P1Component } from './p1.component';

@Component({
    selector: 'app',
    templateUrl: './app/app.template.html',
    directives: [ROUTER_DIRECTIVES]
})

@Routes([
    { path: '/', component: HomeComponent },
    { path: '/p1', component: P1Component }
])

export class AppComponent implements OnInit {

    constructor(public router: Router){ }

    isActiveRoute(route: string) {
        return this.router.serializeUrl(this.router.urlTree) == this.router.serializeUrl((this.router.createUrlTree([route])));
    } 
}

App.template.html:

            <ul class="nav navbar-nav">
                <li [class.active]="isActiveRoute('/')">
                    <a class="nav-link" [routerLink]="['/']">Home</a>
                </li>
                <li [class.active]="isActiveRoute('/p1')">
                    <a class="nav-link" [routerLink]="['/p1']">Page 1</a>
                </li>

Upvotes: 6

iuristona
iuristona

Reputation: 927

Just check the auto-defined router-link-active class to a element.

Upvotes: 8

Alex Santos
Alex Santos

Reputation: 2950

I've been trying to set the active class without having to know exactly what's the current location (using the route name). This is the best solution I have got to so far.

This is how the RouteConfig looks like (I've tweaked it a bit to look like what you want to do):

@RouteConfig([
  { path: '/', component: HomePage, as: 'Home' },
  { path: '/signin', component: SignInPage, as: 'SignIn' },
  { path: '/profile/:username/feed', component: FeedPage, as: 'ProfileFeed' },
])

And the View would look like this:

<li [class.active]="router.isRouteActive(router.generate(['/Home']))">
   <a [routerLink]="['/Home']">Home</a>
</li>
<li [class.active]="router.isRouteActive(router.generate(['/SignIn']))">
   <a [routerLink]="['/SignIn']">Sign In</a>
</li>
<li [class.active]="router.isRouteActive(router.generate(['/ProfileFeed', { username: user.username }]))">
    <a [routerLink]="['/ProfileFeed', { username: user.username }]">Feed</a>
</li>

This has been my preferred solution for the problem so far, it might be helpful for you as well.

Upvotes: 5

Related Questions