2

I'm using the InputrouterLinkActive to add active class to some specific url. But I want that specific link is always active if it detect a chunck of word. Let I explain: if my defined route is /rent/page/:id, and into my template, I do this:

 <a [routerLinkActive]="['active']" [routerLink]="['/rent/page/1']" title="">rent</a>

It works if the url in the adress bar match the defined route, and it adds active class. My main navigation which contains rent link will be active.

But I want more, if my routed has this definition /rent/:property/:name/:id, and I tap the url, it doesn't add the active link to my main navigation.

I found the following solution:

   // ...
   this._router.events.subscribe(
        (urlObj) => {
            if(urlObj.url.match(/^(\/rent).*$/)) {
                this.active["rent"] = true;
            }
        }
    )
    // ...

Every time I match rent into the current url, I set property rent to the object active and it adds active to my rent navigation. And the template mentionned before, I change it as follow:

<a [class.active]="active['rent']" [routerLink]="['/rent/page/1']" title="">rent</a>

And it works, but I'm not sure, if this is a good practice or not.

My question is: How to routerLinkActive if I want to keep specific link active, even if user changes the page? Is there an alternative way to do this using [routerLinkActive] ?

Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60

1 Answers1

0

This can be done like this with router-link:

<router-link :to="{name :'root'}">Root</router-link>
<router-link :to="{name :'foo'}">Go to Foo</router-link>
<router-link to="to="/bar">Go to Bar</router-link>

/bar">Go to Bar

Checkout the following fiddle: http://jsfiddle.net/xgrjzsup/3276/