SASS Theming on Angular

Viewed 61

Following the question How to implement switchable themes in scss? (especially the 2nd answer with ideas from this Medium post), I tried to implement themes through SASS on my project.
But I cannot make it work.


I created a stackblitz so that it is easier to explain and to see the problem:

On the main component, it is working as intended, switching theme in app.component.html (between theme-one and theme-two) changes the color of the <p>.

But on the sub-component (called <my-component>), the same rules are imported in the SASS file but it is not working there.
The underline rule (which is declared in the mixin) is seen, so it has been imported, but the colors are not changing when switching themes.
If I debug (in SASS using @debug), I can see that the colors are rightly fetched from the $theme-map, but it looks like they are not returned.


Is this a known issue linked to Angular encapsulation/scoping? Is there a way to make it work?

1 Answers

This is due to Angular's encapsulation.
As the themes are defined in app.commponent, the rules generated through the SASS mixin will only work in this file.

If you want the mixin throughout your project, you'll have to either change the encapsulation of your components, or use the (deprecated) selector ::ng-deep which makes it global in your app:

@mixin themify($themes: $themes) {
  @each $theme, $map in $themes {
    // ↓ here 
    ::ng-deep .theme-#{$theme} & {
      
    }
  }
}

Here is an updated stacbklitz with this modification.
You can see that the theme system is now working globally.

Related