Jake11
Jake11

Reputation: 831

Angular5, setting active class for RouterLink

I am trying to distinguish currently selected routerLink from others by giving it class which will change some styles.

So in html i added some properties and event to links.

app.component.html:

<nav class="nav-list">
  <a routerLink="/dashboard" 
     class="nav-link" 
     [class.activePage]="pageSelected === 'dashboard'" 
     (click)="setActivePage('dashborad')" >
     Dashboard</a>
  <a routerLink="/products" 
     class="nav-link" 
     [class.activePage]="pageSelected === 'products'" 
     (click)="setActivePage('products')" >
  Products List</a>
</nav>

and in typescript I have implemented variable and method.

app.component.ts:

import { Component } from '@angular/core';


@Component({   selector: 'app-root',   templateUrl: './app.component.html',   styleUrls: ['./app.component.css'] }) 
  export class AppComponent {

  pageSelected:string;

  setActivepage(page){
    this.pageSelected = page;   }

}

but there is nothing happening after link click although activePage class is already set in styles.

Somebody got an idea how to make it work ?

Upvotes: 0

Views: 7158

Answers (3)

Santosh Singh
Santosh Singh

Reputation: 569

<nav class="nav-list">
  <a routerLink="/dashboard" 
     class="nav-link" 
     routerLinkActive="activeClass"
     (click)="setActivePage('dashborad')" >
     Dashboard</a>
  <a routerLink="/products" 
     class="nav-link" 
     routerLinkActive="activeClass"
     (click)="setActivePage('products')" >
  Products List</a>
</nav

Upvotes: 0

zgue
zgue

Reputation: 3850

@vikas and @Mertcan Diken already showed you the solution! I show you how you should use it.

The 'angular' router knows which route is active and will set a class on the active a tag for you. You only have to define which class should be set.

.css

.active-route {
    background: black;
    border-bottom: 2px solid red;      
}

.html

<nav class="nav-list">
    <a routerLink="/dashboard" routerLinkActive="active-route" class="nav-link" >Dashboard</a>
    <a routerLink="/products" routerLinkActive="active-route" class="nav-link">Products List</a>
</nav>

Upvotes: 4

Mertcan Diken
Mertcan Diken

Reputation: 15371

https://angular.io/api/router/RouterLinkActive

You just need to use routerLinkActive prop for that on your routerLink's.

Upvotes: 3

Related Questions