如何从 Angular 中我们自己的组件中添加或删除外部库组件的 CSS class

How to add or remove CSS class of an external library component from our own component in Angular

我有一个具有外部库组件的组件。我想根据我自己的组件中的某些条件更改外部库组件的开关一 class。因此,在这里,我不能使用 ngClass。我可以使用 document.querySelector 但我不想使用它。还有其他办法吗?

您可以使用 ViewChild in your component class to reference the external library component, configuring ViewChild's read option to give you the component as an ElementRef,这样您就可以切换 DOM 元素 class。

例如,如果组件模板中的外部组件如下所示:

<div>
  <external-component class="toggle-me"></external-component>
</div>

您可以将模板引用变量附加到它,如下所示:

<div>
  <external-component #exComp class="toggle-me"></external-component>
  <!--                ^^ add this template reference variable  -->
</div>

然后在您的组件 class 中,使用 ViewChild 获取使用该模板引用变量的外部组件,指定 { read: ElementRef } 这样您就可以获得它的 DOM 元素而不是它的组件 class 实例:

@ViewChild('exComp', { read: ElementRef }) externalComponent: ElementRef;

这样,您就可以访问 nativeElement 及其 classList 来切换 class:

this.externalComponent.nativeElement.classList.toggle('toggle-me');

或者,如果您不想或无法添加模板引用变量,您可以将外部组件的 class 名称而不是模板引用变量名称传递给 ViewChild。

@ViewChild(ExternalComponent, { read: ElementRef }) externalComponent: ElementRef;

Here's a StackBlitz 显示两个选项。