在 Angular 2 中,如何将自定义类分配给活动的路由器链接? [英] In Angular 2 how do I assign a custom class to an active router link?

查看:24
本文介绍了在 Angular 2 中,如何将自定义类分配给活动的路由器链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定路由链接:

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

当路径匹配名为Main"的路由时,框架会自动分配类router-link-active.如果我想给它一个自定义类(可能不需要在控制器中注入 Location 或任何其他服务)怎么办?

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

推荐答案

AFAIK 这不是直接支持的.作为一种解决方法,您可以添加一个指令来检查是否设置了 router-link-active 类,并根据该指令添加/删除您的自定义类.

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 示例

要使用它,只需将其添加到父组件的指令中即可.(未测试)

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

这篇关于在 Angular 2 中,如何将自定义类分配给活动的路由器链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆