Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2+ - change css based on route

Tags:

css

angular

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?

like image 279
Doua Beri Avatar asked Jan 05 '23 15:01

Doua Beri


2 Answers

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

like image 139
VadimB Avatar answered Jan 17 '23 00:01

VadimB


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.

like image 34
Francisco Cabral Avatar answered Jan 17 '23 00:01

Francisco Cabral