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
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.
someElement.classList.contains('foo')does it for me