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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With