Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle multiple themes in an angular component?

I'm working on an Angular 9 project where I'm creating two themes and each theme has it's own css output file. I modified the angular.json file to handle that:

"styles": [
  {
    "input": "src/styles/themes/light-theme.scss",
    "lazy": true,
    "bundleName": "light-theme"
  },
  {
    "input": "src/styles/themes/dark-theme.scss",
    "lazy": false,
    "bundleName": "dark-theme"
  }
],

light-theme and dark-theme are my input files, where I'm setting variables like:

  • $background-color
  • $button-color
  • $text-color
  • etc, etc.

My problem is that I cannot use those variables from each component, because my component won't know what those variables are. I cannot import one or another theme, because I would like to use the values that I declared in the input file. How should I handle this? Is there any way of "importing" the input file I wrote on my angular.json file?

Thanks!

like image 591
Fede Snieg Avatar asked May 15 '20 19:05

Fede Snieg


1 Answers

If you define sass variables in your global styles, you won't be able to access them after when you dynamically change the theme. This is because the dynamically loaded theme will contain css rules only, not sass; besides at run time your components scss has also already compiled to css so there is no more notions of sass variables either way.

What you can do instead is use CSS variables, which have good browser support (apart from IE and opera mini).

So for instance, you can define these variables in your theme files

dark-theme.scss

:root{
  --button-background: darkgrey;
  --button-color: white;
}

light-theme.scss

:root{
  --button-background: lightgrey;
  --button-color: black;
}

Then in your component, use these variables

component.scss

button
{
  cursor: pointer;
  padding: 10px;
  border: 0;
  color:var(--button-color);
  background-color:var(--button-background);
}

Then, when you dynamically load the light theme, it will override the existing variables. If you then dynamically remove light-theme.css, it'll go back to using your dark theme's variables.

like image 124
David Avatar answered Oct 27 '22 15:10

David