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

1

2

We are using a class on the html-element to determine whether the user is in dark or light mode of the app.

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

This class is added using Renderer2 in a service that detects the selected setting of the user. 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.


What we thought would come in handy, is to simply update the SCSS of the component:

.headline {
    color: black;

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

Or in plain 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.


How can we solve this problem?

Maleki answered 21/2, 2020 at 12:37 Comment(2)
You're probably looking for :host-context angular.io/guide/component-styles#host-contextSibeal
@Z.Bagley Wow, now this is excatly what I was looking for. Thanks a lot. Could you add this as an answer? Might be helpful for other people too. :)Maleki
S
3

:host-context provides access to css classes above the :host. 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(.dark-mode) h2 {
  color: white;
}

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

Sibeal answered 21/2, 2020 at 13:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.