Overview
TheThemeService manages the application’s theme state, providing dark mode toggling functionality with localStorage persistence. It also handles server-side rendering compatibility.
Location: src/app/core/services/theme.service.ts
Properties
isDarkMode
true when dark mode is active, false otherwise.
isBrowser
Methods
toggleDarkMode()
Toggles between light and dark mode, updates the DOM, and persists the preference to localStorage. Signature:- Toggles the
isDarkModeproperty - Adds or removes the
dark-modeclass from the document body - Saves the preference to localStorage as a string
- Only executes DOM and localStorage operations in browser environments
initializeTheme()
Initializes the theme based on the user’s saved preference in localStorage. Should be called on application startup. Signature:- Reads the
darkModevalue from localStorage - Sets
isDarkModeproperty based on saved preference - Applies the
dark-modeclass to the document body if dark mode was previously enabled - Only executes in browser environments
currentMode
Getter property that returns the current theme mode. Signature:boolean - The current value of isDarkMode
Example:
localStorage Integration
The service persists theme preferences using the browser’s localStorage API: Storage Key:darkMode
Storage Value: String representation of boolean ('true' or 'false')
Write Operation:
Server-Side Rendering (SSR) Compatibility
The service uses Angular’sPLATFORM_ID injection token to detect the platform:
if (this.isBrowser) checks to prevent errors during server-side rendering.
Usage Pattern
Complete Example
Implementation Details
- The service is provided in the root injector (
providedIn: 'root') - Uses the
dark-modeCSS class on the<body>element to apply theme styles - Platform-aware to support Angular Universal (SSR)
- Automatically persists user preference across sessions