Search code examples
cssangularsassangular2viewencapsulation

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 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?


Solution

  • :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