问题
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