Creating and Unit Testing a Theme Switcher Directive in Angular

Rik de Vos
Devjam
Published in
12 min readApr 29, 2019

--

Photo from unsplash.com

Introduction

A while ago I needed a theme/style switcher which could switch themes during runtime. For example, with Theme A activated my buttons would be red, but with Theme B activated my buttons would change from red to blue. There are various ways of accomplishing this, so I decided to do some Googling. A few popular solutions proposed were:

  • Applying a CSS class to the <body> with the theme name. Then use that CSS class to overwrite CSS properties for elements with specific classes, or load a completely different stylesheet for each theme.
  • Applying a CSS class to each element with the theme name, then style the element for each possible theme.
  • Use inline conditional styles on each element.
  • Use CSS variables to build a theme. This looked promising, but unfortunately no IE11 support 😣.

As you can see many of the solutions require the use of conditional classes or styles, which gets very messy very quickly with many different themes. The solution must also be cross-browser compatible, so no CSS variables unfortunately.

Instead I decided to build a directive which I could apply to any component, and which binds CSS properties to the selected theme properties. For example, the…

--

--

Rik de Vos
Devjam

My name is Rik, a developer and designer living in The Netherlands. Currently I work for CarePay as Lead Front-End Developer. Building stuff is my hobby!