4

Given a routing link:

<li [routerLink]="['Main']"><a>Main page</a></li>

The framework automatically assigns the class router-link-active when the path matches the route named "Main". What if I wanted to give it a custom class (possibly without injecting Location or any other service in the controller)?

Marco Gagliardi
  • 565
  • 1
  • 8
  • 24

2 Answers2

4

AFAIK this isn't supported directly. As a workaround you could add a directive that checks if the class router-link-active is set and depending on that add/remove your custom class.

@Directive({
  selector: '[routerLink]')
export class RouterLinkReplaceClass {
  // add class `my-active` when `myActiveClass` is `true`
  @HostBinding('class.my-active') 

  // read `router-link-active` class state
  @Input('class.router-link-active') 

  myActiveClass: bool = false;
}

Plunker example

To use it just add it to the directives of the parent component. (not tested)

Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

I found something to handle this in an AngularClass project. Check out the custom RouterDirective. Seems to be a way to to get this handled, but I haven't put it to my project yet.

P.J.Meisch
  • 18,013
  • 6
  • 50
  • 66