简体   繁体   English

Angular:如何从 elementRef 判断元素是否应用了给定的类?

[英]Angular: How to tell from elementRef whether element has given class applied to it?

In my Angular app, I have a component that triggers an event when I click on it.在我的 Angular 应用程序中,我有一个组件,当我点击它时会触发一个事件。 I can get the elementRef from this event, but I want to test whether that element has a certain class applied to it.我可以从此事件中获取elementRef ,但我想测试该元素是否应用了某个类。 So my code looks like this:所以我的代码看起来像这样:

<component1 [class.class1]="this.condition">

and

@HostListener('document:mousedown', ['$event'])
  onMouseDown(event: MouseEvent): void {
    let elementRef = this.elementRef;
    // I want to know if 'elementRef' has class 'class1' applied to it.
  }

I want to do something like elementRef.class1 .我想做类似elementRef.class1事情。 Does anyone know how to approach this?有谁知道如何解决这个问题?

You need to get nativeElement (via elementRef's nativeElement property) and then use standard classlist.contains approach:您需要获取 nativeElement(通过 elementRef 的 nativeElement 属性),然后使用标准的 classlist.contains 方法:

elementRef.nativeElement.classList.contains(class);

Not entirely sure of your use case, but if you want to "control" which class is enabled for your component you can leverage ngClass and bind each class to a condition in your ts:不完全确定您的用例,但如果您想“控制”为您的组件启用哪个类,您可以利用 ngClass 并将每个类绑定到您的 ts 中的条件:

<component1 [ngClass]="{ 'class1': isCondition1, 'class2': isCondition2 }"></component1>

So if your isCondition1 property results in 'true' then component1 will have class1 added to it etc因此,如果您的 isCondition1 属性结果为“true”,则 component1 将添加 class1 等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM