7

is there any way to check an element has a class for eg in angular1

angular.element(myElement).hasClass('my-class');

How can I achieve the same in angular5

2
  • What is wrong with using Element.classList? Commented Apr 22, 2018 at 15:08
  • 2
    someElement.classList.contains('foo') does it for me Commented May 13, 2019 at 8:21

1 Answer 1

14

Here is an example on how to so this:

import {Component, NgModule, ViewChild, ElementRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'

@Component({
  selector: 'my-app',
  template: `
    <div>
      <div class="bar" #myDiv>Div with a class</div>
    </div>
  `,
})
export class App {
  @ViewChild('myDiv') myDiv: ElementRef;

  ngOnInit() {
    console.log('has class foo', this.myDiv.nativeElement.classList.contains('foo')) //false
    console.log('has class bar', this.myDiv.nativeElement.classList.contains('bar')) //true
  }
}

As you can see from the code, you annotate the element you need to reference with a #{name} and then use ViewChild() in your template to reference it. In ngOnInit, you can access the nativeElement on the ViewChild and with basic DOM querying you can find out if the class is there.

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

1 Comment

It's an old thread but for the record this.myDiv should not be used on ngOnInit(). It will be initialized on ngAfterViewInit()

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.