简体   繁体   English

Angular2 - 检查是否使用@HostListener 添加到指令中的新类

[英]Angular2 - Check if a new class added to the directive with @HostListener

I have a directive and I want to detect if x class is added to the DOM element which uses that directive.我有一个指令,我想检测是否将x类添加到使用该指令的 DOM 元素中。 For example, let say I have a link例如,假设我有一个链接

<a myLink class="">A link</a>

Then, active class is added to that element from a javascript然后,将active类从javascript添加到该元素

<a myLink class="active">A link</a>

I want to detect this class in MyLink directive.我想在 MyLink 指令中检测这个类。 I tried something like我试过类似的东西

  @HostListener('class',['active'])
  onVisible(){
    console.log("Element active");
  }

But not surprisingly, it's not working.但毫不奇怪,它不起作用。 How can I do that with a HostListener or any other way?我怎么能用HostListener或任何其他方式做到这一点?

@HostListener() is only for events. @HostListener()仅用于事件。

You can use ngDoCheck like您可以使用ngDoCheck类的

export class MyClass implements DoCheck {
  constructor(private elRef:ElementRef) {
    console.log('myClass');
  }

  ngDoCheck() {
    console.log('classList: ' + this.elRef.nativeElement.classList);
  }
}

Plunker examplePlunker 示例

See also https://angular.io/docs/ts/latest/api/core/index/DoCheck-class.html另见https://angular.io/docs/ts/latest/api/core/index/DoCheck-class.html

EDIT: Use [( )] for two way binding.编辑:使用 [( )] 进行双向绑定。 Through this syntax, any changes to DOM will become available in your component通过此语法,对 DOM 的任何更改都将在您的组件中可用

html: html:

<a myLink [(class)]="status">A link </a>

In your component class:在您的组件类中:

private status: String;
...

if (status=='active') {
   //the class is active
}else{//class is something else
}

Original:原来的:

Generally you assign the class through logic in your component.通常,您通过组件中的逻辑分配类。 I suggest you review your approach and see if you can do something like this:我建议你回顾一下你的方法,看看你是否可以做这样的事情:

In your component class:在您的组件类中:

private status: String;
...

if (condition) 
this.status = "active"
else 
this.status = ""

html: html:

<a myLink [class]="status">A link </a>

hope it helps希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM