Reputation: 557
I am using ViewChild directive and get element reference.
How can I get html elements classes inside Angular Component ?
How can I get html elements custom classes (not the classes that create angular) inside Angular Component ?
Upvotes: 0
Views: 16120
Reputation: 578
If you are asking for just getting and settings classes from any HTML elements like div etc. you can use ElmentRef in angular.
You can use template variable (i.e. #useThisTemplateVar) to get HTML element and simply target that element with @ViewChild() decorator.
import { Component, ElementRef, ViewChild } from "@angular/core";
@Component({
selector: "app-example",
template: `
<div #useThisTemplateVar class="myClass">
My some other content!
</div>
<button type="button" (click)="changeClass()">change class</button>
`,
styleUrls: ["./example.component.scss"]
})
export class ExampleComponent implements {
@ViewChild('useThisTemplateVar') elRef: ElementRef;
changeClass(): void {
this.elRef.nativeElement.className === "myClass" ?
this.elRef.nativeElement.className = "yourClass" :
this.elRef.nativeElement.className = "myClass";
}
}
Note: As per angular Security guide you should stop using direct access to DOM elements to prevent XSS attacks to your Web Application.
Learn More: ElementRef Angular official documentation, Angular security Guide
Upvotes: 5
Reputation: 184
this.viewChild.nativeElement.classList
This way you can get your Class list as array.
Upvotes: 2