Clément Flodrops
Clément Flodrops

Reputation: 1104

Angular 2 : check if routeName is the current one

I'm working on a project using Angular 2 and I'm facing an issue. I've created a link component and I can use it like this :

<cmp-link [routeName]="['Channel/Add']">Add channel</cmp-link>

This component checks if the current route is the same as the one passed via parameter and if it is, a class is applied. How do I check if the current url is the same as the one provided by the routeName ? Well it's ugly.

this.isCurrentRoute = this.normalize(currentUrl) === this.routeName[0].toLowerCase();

You don't like it ? Me neither. I would like to check if a route is currently activated using it's name.

(In this case, Channel/Add is a route name).

I don't figure out how to do this using a route's name. I've looked at Router and Instruction.

Upvotes: 5

Views: 2661

Answers (1)

Dinistro
Dinistro

Reputation: 5730

Solution for the old router implementation

I think this sould do the job:

router.isRouteActive(router.generate(['Home']))

This is not a very nice solution, but the only one I know.


The router.isRouteActive wants an Instruction and is not able to manage the string itself, so you need to generate this Instruction with router.generate().

Source: https://angular.io/docs/ts/latest/api/router/Router-class.html


Note

As @Clément Flodrops mentioned, this only works with a flat routing-structure. As far as I can see, it's currently not possible to archive this nicely.

Perhaps it would be possible to work with the private _childeRouter of the Router, but to access this property, we would need to override the Router-class.

So I suggest to wait some time, perhaps the Router will support this operation once.


EDIT: new router 3.0.0-alpha

With the new router you can add a routerLinkActive="class" and this will add the class, if the routerLink is active.

Also works, if the routerLink is not directly on the tag with the routerLinkActive:

<li role="menuitem" routerLinkActive="active">
    <a href="" [routerLink]="['/home']" title="home" class="control-icon">
        <span class="fa fa-home"></span>
    </a>
</li>

Upvotes: 4

Related Questions