2

I'm struggling with this and could not find any answer although it seems this is a common scenario.

I'm building a web app in angular5, all styling in less using @component styleUrls.

I use less, and all colors are defined in a global-vars.less file, imported to all encapsulated components.

global-vars.less:

@color_0:  #283238; 

some-component.less:

@import '../../global-vars';
.my-div {
  background-color: @color_0;
}

I would like to add a layer in global-vars.less to switch color by parent class:

global-vars.less:

@color_0:  #283238; 
@color_1:  #EEFFEE; 

.dark-theme {
  @background-app-color: @color_0;
}

.light-theme {
  @background-app-color: @color_1;
}

some-component.less:

@import '../../global-vars';
.my-div {
  background-color: @background-app-color;
}

Of course, it cannot work as LESS pre-compiles everything. But I could not find a technique to work. I tried changing CSS file from the header but because angular uses encapsulated stylesheets inserted as tags this does not help me. I tried using mixins but I cannot create a mixin according to parent class so no luck there.

My only option is to duplicate the all the CSS hierarchy for all modules

.parent {
  .child {
    background: @light-color;
  }
}

.dark theme .parent {
  .child {
    background: @dark-color;
  }
}

but this would be a nightmare to maintain as the project is huge

Any help would be greatly appreciated. Thanks.

agora
  • 21
  • 5
  • I don't know if this could help for your particular Angular project, but [here's](https://stackoverflow.com/a/25877100/2712740) typical predefined themes generation methods with minimal boating. – seven-phases-max Feb 19 '18 at 21:20

1 Answers1

0

I found my answer using CSS custom properties (variables) Apparently, it already has enough support, and using them I can bypass all angular encapsulation problems.

I created a themes.css file which is imported to main.css.

There I have:

:root {
  --light_color_0: #FFF;
  --light_color_1: #EEE;

  --dark_color_0: #000;
  --dark_color_1: #111;
}

And in the same file:

:root {
  --bg_color: var(--light_color_0);
}

:root.darktheme {
  --bg_color: var(--light_color_0);
}

from inside my angular components I have:

.panel_popup {
  background-color: var(--bg_color);
}

and all that is left is to add a class by clicking a button. hope it helps someone

agora
  • 21
  • 5