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??
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) {} ...
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.
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.
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.
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.
Just check the auto-defined router-link-active
class to a
element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With