0

In my Angular app, I have a component that triggers an event when I click on it. I can get the elementRef from this event, but I want to test whether that element has a certain class applied to it. So my code looks like this:

<component1 [class.class1]="this.condition">

and

@HostListener('document:mousedown', ['$event'])
  onMouseDown(event: MouseEvent): void {
    let elementRef = this.elementRef;
    // I want to know if 'elementRef' has class 'class1' applied to it.
  }

I want to do something like elementRef.class1. Does anyone know how to approach this?

1 Answer 1

3

You need to get nativeElement (via elementRef’s nativeElement property) and then use standard classlist.contains approach:

elementRef.nativeElement.classList.contains(class);

Not entirely sure of your use case, but if you want to "control" which class is enabled for your component you can leverage ngClass and bind each class to a condition in your ts:

<component1 [ngClass]="{ 'class1': isCondition1, 'class2': isCondition2 }"></component1>

So if your isCondition1 property results in 'true' then component1 will have class1 added to it etc

Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, thanks! I posted another similar question if you have any insight: stackoverflow.com/questions/59473992/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.