[英]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);
}
}
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.