简体   繁体   English

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

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

We are using a class on the html -element to determine whether the user is in dark or light mode of the app.我们在html元素上使用一个类来确定用户是处于应用程序的dark模式还是light模式。

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

This class is added using Renderer2 in a service that detects the selected setting of the user.此类是在检测用户所选设置的服务中使用Renderer2添加的。 This works fine so far.到目前为止,这工作正常。

Now, we have to adjust all the components to look good in the dark mode as well.现在,我们必须调整所有组件以使其在黑暗模式下也看起来不错。 But the problem is Angular's ViewEncapsulation .但问题是 Angular 的ViewEncapsulation


What we thought would come in handy, is to simply update the SCSS of the component:我们认为会派上用场的方法是简单地更新组件的 SCSS:

.headline {
    color: black;

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

Or in plain CSS:或者在纯 CSS 中:

.headline {
  color: black;
} 

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

Now this doesn't work, because the class .dark-mode seems to be encapsulated, as expected.现在这不起作用,因为.dark-mode类似乎被封装了,正如预期的那样。


How can we solve this problem?我们如何解决这个问题?

:host-context provides access to css classes above the :host . :host-context提供对:host之上的 css 类的访问。 By using :host-context you are able to check if any of the parents of the host have a specific css class and apply styling:通过使用:host-context您可以检查:host-context任何父级是否具有特定的 css 类并应用样式:

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

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

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

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