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

查看:58
本文介绍了在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;
}

柱塞示例

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

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

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

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