Advertisement
Intermediate Angular, Angular Material Theming

How would you implement a light and dark mode toggle using Angular Material theming?

Short answer

You define two separate theme classes, one for light mode and one for dark mode, and toggle a CSS class on your app's root element based on the user's chosen preference.

Save Angular mock interview
Advertisement
AModel answer
You define two separate theme classes, one for light mode and one for dark mode, and toggle a CSS class on your app's root element based on the user's chosen preference. Angular Material's components automatically pick up the correct colors based on whichever theme class is currently active.
// styles.scss
.light-theme { @include mat.all-component-colors($light-theme); }
.dark-theme { @include mat.all-component-colors($dark-theme); }

// In your component
toggleDarkMode() {
  document.body.classList.toggle('dark-theme');
}
Real-world example
A productivity app lets users switch between light and dark mode with a single toggle button, instantly updating the colors of every Angular Material component on the screen without reloading the page.
Likely follow-ups
  • How would you remember the user's chosen theme preference across visits?
  • How do you also detect and respect the user's operating system's dark mode setting automatically?
Related topics