Skip to main content

GdThemeService

The GdThemeService is an Angular service that manages theme switching between light and dark modes in an application.

Import

import { GdThemeService } from '@geodome/gdk/common';

Description

This service provides functionality to:

  • Initialize the theme based on user preference or system settings.
  • Set a specific theme (light or dark).
  • Store the user's theme preference.

Methods

initializeTheme()

Initializes the theme when the application starts. It checks for a saved theme preference in local storage. If none exists, it sets the theme based on the system's color scheme preference.

setTheme(themeName: 'light-mode' | 'dark-mode')

Sets the specified theme by adding the appropriate CSS class to the body element and saving the preference to local storage.

note

Parameters:

  • themeName: 'light-mode' | 'dark-mode' - The theme to be set.

Usage Example

export class AppComponent {
constructor(private themeService: GdThemeService) {
this.themeService.initializeTheme();
}

toggleTheme(theme: 'light-mode' | 'dark-mode') {
this.themeService.setTheme(theme);
}
}

Initialization in App Startup

Typically, the GdThemeService is initialized during the application's startup process. This ensures that the theme is set correctly as soon as the app loads. Here's an example of how to set this up:

  1. Create an initialization function:
import { inject } from '@angular/core';
import { GdThemeService } from '@geodome/gdk/common';
import { GdSettingsService } from '@geodome/gdk/core';
import { map } from 'rxjs';

export function initializeApp() {
const settingsService = inject(GdSettingsService);
const themeService = inject(GdThemeService);

return settingsService.loadConfig().pipe(map(() => themeService.initializeTheme()));
}
  1. Add the initializer to your app.config.ts:
import { ApplicationConfig } from '@angular/core';
import { provideAppInitializer } from '@angular/core';
import { initializeApp } from './initializer';

export const appConfig: ApplicationConfig = {
providers: [
// ... other providers
provideAppInitializer(initializeApp),
]
};

This setup ensures that the theme is initialized right after the application settings are loaded, providing a smooth and consistent theming experience from the moment the app starts.

Key Features

  • Automatically detects system color scheme preference.
  • Persists user theme preference in local storage.
  • Provides easy theme switching functionality.
  • Uses Angular's Renderer2 for DOM manipulation, ensuring platform independence.