Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check element has class in angular5

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

like image 953
shellakkshellu Avatar asked Apr 22 '18 14:04

shellakkshellu


People also ask

How to find element with class in javascript?

The syntax is as follows:var elements = document. getElementsByClassName(name); Here “name” is the class name you are looking to find and “elements” is a variable that would contain the array of elements.


1 Answers

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.

like image 168
nonstopcoding Avatar answered Sep 30 '22 07:09

nonstopcoding