a_main
a_main

Reputation: 557

How can I get html elements classes inside Angular Component?

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 ?

Link to demo example

Upvotes: 0

Views: 16120

Answers (2)

deepchudasama
deepchudasama

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

Dipal
Dipal

Reputation: 184

this.viewChild.nativeElement.classList

This way you can get your Class list as array.

Upvotes: 2

Related Questions