如何根据 Angular 中的全局 CSS class-名称调整组件的 CSS?

How is it possible to adjust a component's CSS based on a global CSS class-name in Angular?

我们在 html 元素上使用 class 来确定用户是处于应用程序的 dark 还是 light 模式。

<html class="dark-mode"></html>

此 class 是使用 Renderer2 添加到检测用户所选设置的服务中。到目前为止效果很好。

现在,我们必须调整所有组件以使其在暗模式下也看起来不错。但问题是 Angular 的 ViewEncapsulation.


我们认为会派上用场的是,只需更新组件的 SCSS:

.headline {
    color: black;

    .dark-mode & {
      color: white;
    }
}

或者简单地说 CSS:

.headline {
  color: black;
} 

.dark-mode .headline {
  color: white;
}

现在这不起作用,因为 class .dark-mode 似乎被封装了,正如预期的那样。


如何解决这个问题?

:host-context 提供对 :host 之上的 css class 的访问。通过使用 :host-context,您可以检查主机的任何 parents 是否具有特定的 css class 并应用样式:

:host-context(.dark-mode) h2 {
  color: white;
}

文档:https://angular.io/guide/component-styles#host-context