【发布时间】:2019-05-12 03:09:03
【问题描述】:
我正在使用 ViewChild 指令并获取元素引用。
如何在 Angular 组件中获取 html 元素类?
如何在 Angular 组件中获取 html 元素自定义类(不是创建 angular 的类)?
【问题讨论】:
-
你能用你的代码的几个sn-ps来详细说明你的问题吗?
-
我已经添加了一些代码sn-ps
标签: angular
我正在使用 ViewChild 指令并获取元素引用。
如何在 Angular 组件中获取 html 元素类?
如何在 Angular 组件中获取 html 元素自定义类(不是创建 angular 的类)?
【问题讨论】:
标签: angular
如果您只要求从任何 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 documentation、Angular security Guide
【讨论】:
this.viewChild.nativeElement.classList
这样你就可以得到你的类列表作为数组。
【讨论】: