Blog>
Snippets

Theme Selection Dropdown with Angular and CSS Variables

Create a dropdown menu using Angular's ngModel to offer a selection of themes. Apply the selected theme by updating CSS variables using the ngOnChanges lifecycle hook.
import { Component, OnInit, OnChanges, SimpleChanges } from '@angular/core';

@Component({
  selector: 'app-theme-selector',
  template: `
    <select [(ngModel)]="selectedTheme" (change)="updateTheme()">
      <option *ngFor="let theme of themes" [value]="theme.value">{{ theme.label }}</option>
    </select>
  `, // Note: In a real-world application, externalize this to an HTML file
  styleUrls: ['./theme-selector.component.css']
})
export class ThemeSelectorComponent implements OnInit, OnChanges {
  themes = [
    { label: 'Light', value: 'light' },
    { label: 'Dark', value: 'dark' },
    // Add more themes here
  ];
  selectedTheme = 'light'; // Default theme

  constructor() { }

  ngOnInit(): void {
    this.updateTheme(); // Set default theme on init
  }

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.selectedTheme) {
      this.updateTheme();
    }
  }

  updateTheme(): void {
    document.documentElement.style.setProperty('--primary-bg-color', this.selectedTheme === 'dark' ? '#000' : '#fff');
    document.documentElement.style.setProperty('--primary-text-color', this.selectedTheme === 'dark' ? '#fff' : '#000');
    // Update more CSS variables as needed
  }
}
This TypeScript code defines an Angular component with a dropdown menu that allows users to select a theme. It uses ngModel to create a two-way data binding for the selected theme, and ngOnChanges to apply changes to the theme by updating CSS variables when the selection changes. The updateTheme method updates the document's CSS variables based on the selected theme.
:root {
  --primary-bg-color: #fff; /* Light theme background color */
  --primary-text-color: #000; /* Light theme text color */
  /* Define more CSS variables for light theme here */

  /* Dark theme variable overrides: */
  [data-theme='dark'] {
    --primary-bg-color: #000; /* Dark theme background color */
    --primary-text-color: #fff; /* Dark theme text color */
    /* Define more CSS variables for dark theme here */
  }
}

body {
  background-color: var(--primary-bg-color);
  color: var(--primary-text-color);
}
This CSS code defines variables in the :root pseudo-class for the default light theme and provides overrides for the dark theme using a data-theme attribute selector. These variables are used to set the background and text colors in the body element, and more variables can be defined and used throughout the application.