5

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?

DilumN
  • 2,889
  • 6
  • 30
  • 44
Doua Beri
  • 10,612
  • 18
  • 89
  • 138
  • Perhaps something similar to http://stackoverflow.com/questions/38644314/changing-the-page-title-using-the-angular-2-new-router/38652281#38652281 – Günter Zöchbauer Jan 31 '17 at 21:11
  • 1
    Have you tried the using the `routerLinkActive` directive on the tab link? I.e. `Tab2`. What you pass to this directive is the name of a CSS class(es) that will get added to the link if it matches the current route. – AngularChef Jan 31 '17 at 21:12

2 Answers2

8

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

VadimB
  • 5,533
  • 2
  • 34
  • 48
2

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.

Francisco Cabral
  • 856
  • 11
  • 21