Reputation: 10949
I'm trying to build a tab menu in Angular (v2.4.5) . A tab is active based on the route.
For example I have this routes:
const routes: Routes = [
{
path: 'tab1',
component: Tab1Component,
},
{
path: 'tab2',
component: Tab2Component,
}
];
if the user enters the address http://localhost/tab2
I want tab2
to be highlighted ( change tab css).
What is the best approach to achieve this?
Upvotes: 5
Views: 7743
Reputation: 5711
RouterLinkActive
Lets you add a CSS class to an element when the link's route becomes active.
<a routerLink="/user/bob" routerLinkActive="class1 class2">Bob</a>
<a routerLink="/user/bob" [routerLinkActive]="['class1', 'class2']">Bob</a>
You can assign the RouterLinkActive instance to a template variable and directly check the isActive status also:
<a routerLink="/user/bob" routerLinkActive #rla="routerLinkActive">
Bob {{ rla.isActive ? '(already open)' : ''}}
</a>
https://angular.io/docs/ts/latest/api/router/index/RouterLinkActive-directive.html
Upvotes: 8
Reputation: 892
Use routerLinkActive="active"
on your links, you will have something like this:
<nav>
<a routerLink="/tab1" routerLinkActive="active">TAB 1</a>
<a routerLink="/tab2" routerLinkActive="active">TAB 2</a>
</nav>
In your CSS you'll add a active
class for your nav links:
nav {
color: black;
}
nav .active {
color: orange;
}
More info about routes here.
Upvotes: 2