I'm using the Input
routerLinkActive 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]
?