androidangularionic-frameworkcapacitorionic7

in ionic v7 and Angular 17, how to toggle between light and dark theme at runtime (dynamically)


I noticed when the phone theme is dark mode the app will be in dark mode by default and vice versa for light mode but I could not understand what's happening behind the scenes and how to switch the theme at runtime.

I have not try anything because I could not understand what is happening behind the scenes so I can implement an approach for this case, thank you.


Solution

  • go to variables.scss file and copy the css of the dark theme and paste in a class, I choose 'dark-theme', then I have defined this Service to handle the the toggle

    @Injectable({
      providedIn: 'root',
    })
    export class ThemeService {
      private renderer: Renderer2;
      private darkThemeClass = 'dark-theme';
    
      constructor(rendererFactory: RendererFactory2) {
        this.renderer = rendererFactory.createRenderer(null, null);
      }
    
      setInitialTheme() {
        const savedThemePreference = localStorage.getItem('isDarkMode');
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
    
        if (savedThemePreference !== null) {
          this.toggleTheme(savedThemePreference === 'true');
        } else {
          this.toggleTheme(prefersDark);
        }
      }
    
      toggleTheme(isDarkMode: boolean) {
        if (isDarkMode) {
          this.renderer.addClass(document.body, this.darkThemeClass);
        } else {
          this.renderer.removeClass(document.body, this.darkThemeClass);
        }
        localStorage.setItem('isDarkMode', isDarkMode.toString());
      }
    }