【问题标题】:How can I get html elements classes inside Angular Component?如何在 Angular 组件中获取 html 元素类?
【发布时间】:2019-05-12 03:09:03
【问题描述】:

我正在使用 ViewChild 指令并获取元素引用。

如何在 Angular 组件中获取 html 元素类?

如何在 Angular 组件中获取 html 元素自定义类(不是创建 angular 的类)?

Link to demo example

【问题讨论】:

标签: angular


【解决方案1】:

如果您只要求从任何 HTML 元素(如 div 等)获取和设置类,您可以在 Angular 中使用 ElmentRef。

您可以使用 模板变量(即#useThisTemplateVar)来获取 HTML 元素并使用 @ViewChild() 装饰器简单地定位该元素。

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"; 
}

}

注意:根据角度安全指南,您应该停止使用对 DOM 元素的直接访问来防止对您的 Web 应用程序的 XSS 攻击。

了解详情:ElementRef Angular official documentationAngular security Guide

【讨论】:

    【解决方案2】:
    this.viewChild.nativeElement.classList
    

    这样你就可以得到你的类列表作为数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-04
      • 1970-01-01
      • 1970-01-01
      • 2019-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多