Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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??

like image 744
Aico Klein Ovink Avatar asked Jan 02 '16 22:01

Aico Klein Ovink


People also ask

How does Angular determine active routes?

Show activity on this post. You can check the current route by injecting the Location object into your controller and checking the path() , like so: class MyController { constructor(private location:Location) {} ...

How do you access the parameters passed to a route in Angular?

We can use get or getAll methods to retrieve the value of the parameters in the component. Use the has method to check if a certain parameter exists. The Older version of ActivatedRoute class has a Params array which is an array of the parameter values, indexed by name.

How does Angular routing handle route parameters?

To access the route parameters, we use route. snapshot , which is the ActivatedRouteSnapshot that contains information about the active route at that particular moment in time. The URL that matches the route provides the productId . Angular uses the productId to display the details for each unique product.

How will you extract route parameters?

To extract the parameter, you need to make the dynamic parameter in the route path so that you can extract the value of the parameter by parameter name.


2 Answers

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.

like image 135
Michael Oryl Avatar answered Sep 25 '22 18:09

Michael Oryl


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

like image 36
iuristona Avatar answered Sep 23 '22 18:09

iuristona