简体   繁体   中英

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. 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

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

I want to detect this class in MyLink directive. 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() is only for events.

You can use ngDoCheck like

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

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

Plunker example

See also 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

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:

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

hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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