Mar 14, 2019 · 3 min read #Design · #Angular

Dynamically Changing CSS Theme in Angular

angular dynamic color change
MVP theme changing modal

One of the requirements for my latest project,, was to allow the user to dynamically change the primary highlight color sitewide. There's a number of ways this could be accomplished. Let's take a look at the three I tried.

1. Injecting an alternative stylesheet

<link rel="stylesheet" [href]='sanitizer.bypassSecurityTrustResourceUrl(cssUrl)' />

This is definitely an acceptable way to change color themeing. We change dynamically change the url of the loaded CSS file after telling Angular to trust the sanitizer to trust the resource url. At that point all we'd need to do is create a stylesheet per theme that we would have.

And there's the problem. We may have 6 theme options now, but we may have 12, 24, etc in the future. I don't want N number of stylesheets taking up valuable build space. I like my apps lean. Not to mention that in general bypassing Angular's security safeguards isn't ideal.

2. Change the SASS variable value of the primary highlight color

  get style() {
    return this.sanitizer.bypassSecurityTrustStyle(`
      --primary: ${this.activeColor};

This method seemed promising at first. With HostBinding we can set a global SASS variable that can be accessed by any other SCSS file. In any other component that wants to use this variable we simply do:

color: var(--primary);

But what if we need the color to change dynamically as the user changes from blue to red to yellow in a kind of "preview". Well there's the problem with #2: You can't. Trying to run the bypassSecurityTrustStyle again as the user clicks different themes does not change the variable globally. We either have to reload the page or the component.

3. Use a mixin that operates off the container class

@mixin theme($color) {
  .text-color {
    color: $color;
.accent-color-red {
    @include theme(#f62862);

SASS is amazing. I have gone more into depth about my favorite features, but mixins are just so powerful. Here we simply use Angular to change the class of the parent container on the entire app when a user clicks their preferred color and voila everything changes neatly.

Of course the real mixin we use for Mainline includes another 60 lines, but all we need to do to add more theme options is simply write another class and define its HEX value.

I'd absolutely love to know of more alternatives, so if you're inclined shoot me a tweet or comment below!

&More Articles

Mar 2, 2019 · 2 min read

Best SASS Mixins & Functions

My personal favorite mixins and functions I use in every single application I develop.