0

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

3
  • Can you elaborate your question with a few snippets of your code? Commented Dec 11, 2018 at 6:53
  • How to create a Minimal, Complete, and Verifiable example Commented Dec 11, 2018 at 6:56
  • I am already add some code snippets Commented Dec 11, 2018 at 7:01

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

Comments

2
this.viewChild.nativeElement.classList

This way you can get your Class list as array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.