HappyCoder
HappyCoder

Reputation: 6155

Angular2 - Show link as active for two routes

I want a route to be active for either: "www.example.com" or "www.example.com/route-name".

I know I can simply re-direct from / to /route-name however I just cant help but feel this is bad practice and it would be the code directing the logic...

To show a route is active I have the following for route-name:

<a [routerLink]="['route-name']"><span>Route Name</span></a>

If this where PHP I would do something like:

($route == '/' OR $route == 'route-name') ? 'active' : ''

How do you do this sort of condition with NG2?

Upvotes: 0

Views: 95

Answers (1)

Aravind
Aravind

Reputation: 41581

You can handle this using [class] property binding,

<a [routerLink]="['route-name']" [ngClass]="{'active': activeLink}"></a>

In your menu component ngOnChanges,check for the router's path and then assign true to activeLink as

if(this.router...){
this.activeLink=true;
}

Upvotes: 1

Related Questions