Blog>
Snippets

Toggling Dark and Light Themes with Angular

Demonstrate how to toggle between dark and light themes using a button. Utilize CSS variables to set different color schemes and Angular's NgClass to switch themes.
/* app.component.ts */
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  theme: string = 'light-theme';

  toggleTheme() {
    this.theme = this.theme === 'light-theme' ? 'dark-theme' : 'light-theme';
  }
}
This TypeScript snippet defines an Angular component with a toggleTheme method to switch the theme class name between 'light-theme' and 'dark-theme'.
/* app.component.html */
<div [ngClass]="theme">
  <!-- Content of your component -->
  <button (click)="toggleTheme()">Toggle Theme</button>
</div>
The HTML template for the Angular component. It uses the ngClass directive to apply the current theme and a button to switch themes.
/* styles.css (global styles) */
:root {
  --background-light: #fff;
  --background-dark: #000;
  --text-light: #000;
  --text-dark: #fff;
}

.light-theme {
  --background: var(--background-light);
  --text-color: var(--text-light);
}

.dark-theme {
  --background: var(--background-dark);
  --text-color: var(--text-dark);
}

body {
  background-color: var(--background);
  color: var(--text-color);
}
The global CSS styles define the CSS variables for light and dark themes and set up the respective classes to be applied to the body or any targeted element to change its appearance based on the theme selected.