DEV Community

Cover image for Toggle dark theme in Angular Material
Dharmen Shah for Angular Material Dev

Posted on

Toggle dark theme in Angular Material

In one of our previous articles, we saw how to lazy load a dark theme. If you haven't already, please check it first:

Now, to load the "dark-theme.css" based on user's choice, we will create a simple service called "StyleManager":

// style-manager.service.ts

import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class StyleManager {
  isDark = false;

  toggleDarkTheme() {
    if (this.isDark) {
      this.removeStyle('dark-theme');
      document.body.classList.remove('dark-theme');
      this.isDark = false;
    } else {
      const href = 'dark-theme.css';
      getLinkElementForKey('dark-theme').setAttribute('href', href);
      document.body.classList.add('dark-theme');
      this.isDark = true;
    }
  }

  removeStyle(key: string) {
    const existingLinkElement = getExistingLinkElementByKey(key);
    if (existingLinkElement) {
      document.head.removeChild(existingLinkElement);
    }
  }
}

function getLinkElementForKey(key: string) {
  return getExistingLinkElementByKey(key) || createLinkElementWithKey(key);
}

function getExistingLinkElementByKey(key: string) {
  return document.head.querySelector(
    `link[rel="stylesheet"].${getClassNameForKey(key)}`
  );
}

function createLinkElementWithKey(key: string) {
  const linkEl = document.createElement('link');
  linkEl.setAttribute('rel', 'stylesheet');
  linkEl.classList.add(getClassNameForKey(key));
  document.head.appendChild(linkEl);
  return linkEl;
}

function getClassNameForKey(key: string) {
  return `style-manager-${key}`;
}
Enter fullscreen mode Exit fullscreen mode

Then you can inject the "StyleManager" service, and call "toggleDarkTheme" whenever you want!

// src/app/app.component.ts

import { Component } from '@angular/core';
import { StyleManager } from './services/style-manager.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  title = 'my-app';
  isDark = this.styleManager.isDark;

  private styleManager = inject(StyleManager);

  toggleDarkTheme() {
    this.styleManager.toggleDarkTheme();
    this.isDark = !this.isDark;
  }
}
Enter fullscreen mode Exit fullscreen mode

That's it!!! For more information, read full article at:

Top comments (0)