Implementing Dark Mode Support in Angular Applications

Dark mode has become a popular feature in modern web applications, offering users a comfortable viewing experience, especially in low-light environments. Implementing dark mode support in Angular applications enhances user satisfaction and accessibility. This article guides you through the essential steps to add dark mode functionality to your Angular project.

Understanding Dark Mode in Angular

Dark mode involves switching the application’s color scheme from light to dark, typically by toggling CSS classes or variables. Angular provides flexible tools to implement this feature, such as services, directives, and theming strategies. The goal is to allow users to toggle between modes seamlessly, with the UI updating dynamically.

Steps to Implement Dark Mode

  • Create a theme service: Manage the current theme state and provide methods to toggle themes.
  • Define CSS variables: Use CSS custom properties for colors, backgrounds, and other styles that differ between themes.
  • Apply theme classes: Add or remove classes on the <body> or main container based on the theme state.
  • Implement toggle controls: Provide UI elements like switches or buttons for users to switch themes.
  • Persist user preference: Save the theme choice in local storage or cookies to maintain consistency across sessions.

Example Implementation

Start by creating a ThemeService to manage theme state:

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

@Injectable({
  providedIn: 'root'
})
export class ThemeService {
  private isDarkMode = false;

  constructor() {
    const savedTheme = localStorage.getItem('theme');
    this.isDarkMode = savedTheme === 'dark';
    this.updateBodyClass();
  }

  toggleTheme() {
    this.isDarkMode = !this.isDarkMode;
    localStorage.setItem('theme', this.isDarkMode ? 'dark' : 'light');
    this.updateBodyClass();
  }

  private updateBodyClass() {
    const body = document.body;
    if (this.isDarkMode) {
      body.classList.add('dark-mode');
      body.classList.remove('light-mode');
    } else {
      body.classList.add('light-mode');
      body.classList.remove('dark-mode');
    }
  }
}

Next, define CSS variables for themes:

/* styles.css */
:root {
  --background-color: #ffffff;
  --text-color: #000000;
}

body.dark-mode {
  --background-color: #121212;
  --text-color: #ffffff;
}

body {
  background-color: var(--background-color);
  color: var(--text-color);
}

Finally, add a toggle button in your component template:

This simple setup allows users to switch themes, with styles updating instantly. You can enhance this by adding animations, icons, or saving preferences for a more polished experience. Implementing dark mode in Angular not only improves usability but also aligns your app with modern design standards.