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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With