In Angular 2 how do I assign a custom class to an active router link? [duplicate]

﹥>﹥吖頭↗ 提交于 2019-11-27 06:21:53

问题


This question already has an answer here:

  • Changing the default name of “router-link-active” class by writing a custom directive that adds new class 2 answers

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)?


回答1:


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)




回答2:


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.



来源:https://stackoverflow.com/questions/34965853/in-angular-2-how-do-i-assign-a-custom-class-to-an-active-router-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!