Blog>
Snippets

User Preference-Based Theming in Angular with Local Storage

Demonstrate saving the user's preferred theme to local storage and applying it on the app's load. Use CSS variables in Angular to reflect the saved theme preferences.
constructor(private renderer: Renderer2) {
  this.loadTheme();
}
In the Angular component's constructor, call the loadTheme() method to apply the stored theme when the component is created.
loadTheme(): void {
  const theme = localStorage.getItem('user-theme') || 'default-theme';
  this.applyTheme(theme);
}
The loadTheme method retrieves the theme preference from local storage (or defaults to 'default-theme') and applies it using the applyTheme method.
applyTheme(theme: string): void {
  const themeClass = `theme-${theme}`;
  this.renderer.removeClass(document.body, 'theme-default');
  this.renderer.removeClass(document.body, 'theme-dark');
  // Add other theme class names to remove if you have more themes
  this.renderer.addClass(document.body, themeClass);
}
The applyTheme method modifies the document body's class list to reflect the desired theme using the Renderer2 service, removing previous theme classes and adding the selected theme class.
setTheme(theme: string): void {
  localStorage.setItem('user-theme', theme);
  this.applyTheme(theme);
}
The setTheme method saves the user's preferred theme to local storage and applies it to the document.
/* Example usage in a component method triggered by a user action (e.g., button click) to change the theme */
changeTheme(newTheme: string): void {
  this.setTheme(newTheme);
}
This example method illustrates how you might trigger a theme change in response to a user action, such as clicking a button to choose a new theme.
:root {
  --background-color: #ffffff;
  --text-color: #000000;
}

.theme-dark {
  --background-color: #000000;
  --text-color: #ffffff;
}
This CSS snippet provides an example of defining CSS variables for a default theme and a dark theme that can be toggled using the classes applied to the document body in the JavaScript code provided.