Disclaimer: css vars are awesome but the way I use them in this post is not the best “angular-way” since I’m using elementRef.nativeElement instead of rendere2, currently (Feb 2019 ) it seems that renderer.setStyle() wont work with css vars..

this.renderer.setStyle(this.elementRef.nativeElement, key, theme[key]);

**/

Recently I started using css custom properties (css variables) on my sweet tiny side project (a “trello” like draggable tasks board hosted on firebase + firestore).

It’s really nice and easy! I implemented an app“ theming” feature which gives the app a different look and feel dynamically by just a toggle button click (currently only 2 themes available hardcoded — next is to give the user the option to set any color he wants! the power of using variables!).

CSS variables / Custom properties are:

Property names that are prefixed with -- , like --example-name , represent custom properties that contain a value that can be used in other declarations using the var() function

Example:

Declare: :root {

--first-color: #488cff;

--second-color: #ffff8c;

} Use: .some-class {

background-color: var(--first-color);

color: var(--second-color);

}

In Angular:

I made a stackblitz repo shows how to do so in Angular:

I created a theme module which exports the appTheme directive (a bit of an overkill here), the appTheme is used to dynamically change the application theme whenever it notified to do so (add a theme reactive service).

Clicking on the ‘Change Theme’ link will notify the directive that it should change the active theme.

The theme update is done by setting a new value to the custom css properties (aka css vars)

That’s all : elemnt.style.setProperty( ‘ — background’, ‘aliceblue’);