For a while i have been mulling over ways to best achieve dynamic styles in Angular, I was convinced that defining different theme’s in sass variables, then loading in those sass variables depending on some criteria was the way to go.

However lately I have changed my tone, now I look towards RxJs as a way of changing styles for different users. The main reasons for this is that

Themes can be changed at runtime through the implementation of RxJs streams (hence the catchy title).

Theme variables can be read from pretty much any source (.ENV, json, ts-config, api, etc)

This method creates a clear definition between what is dynamically themed and what is statically themed with SCSS (a lot of your styles wont need to be dynamic) helps with single responsibility principle.

My approach centres around NGXS, however the source can be anything, NGRX or even a regular old service. The real meat and potatoes of the system is the dynamic-style directive which i will outline below.

This directive essentially takes a style string (one or more css declarations) as input and assigns them to the element doing a string replace on the input styles with the theme variables stored in state.

It allows us to set multiple dynamic styles per element, whilst still maintaining the initial styles set on the element (useful for things like angular flex which set its own element styles). Whats more is that we can set any style dynamically, we could set box-shadow, border-color, height, etc.

You can see a demo in the code below