Search code examples
angularionic-frameworkangular-materialionic-native

How to toggle dark mode in ionic8 Angular 18


I have three CSS styles in my global.scss file. Currently, I am using dark mode, but I want to change them conditionally. How can I do this in Ionic 8 and Angular 18?

Here is my global.scss code.

// @import "@ionic/angular/css/palettes/dark.always.css";
// @import "@ionic/angular/css/palettes/dark.class.css";
@import '@ionic/angular/css/palettes/dark.system.css';

I want to add one toggle button in my app so i can witch theme according to that.


Solution

  • I find the solution for ionic 8 and angular 18.

    // @import "@ionic/angular/css/palettes/dark.always.css";
    @import "@ionic/angular/css/palettes/dark.class.css"; // uncomment this
    // @import '@ionic/angular/css/palettes/dark.system.css'; // comment this
    

    And toggle the class

    document.documentElement.classList.toggle('ion-palette-dark', theme === 'dark');
    

    Here is my full code which i implemented

    constructor(){
      this.initializeTheme();
    }
    
    initializeTheme() {
      let currentTheme = localStorage.getItem('theme');
    
      if (!currentTheme) {
        // Default to dark theme if no theme is set
        currentTheme = 'dark';
        localStorage.setItem('theme', currentTheme);
      }
    
      this.applyTheme(currentTheme);
    }
    
    toggleTheme() {
      const currentTheme = localStorage.getItem('theme') || 'dark';
      const newTheme = currentTheme === 'dark' ? 'light' : 'dark';
    
      this.applyTheme(newTheme);
      localStorage.setItem('theme', newTheme);
    }
    
    applyTheme(theme: string) {
      // Update theme and toggle the class
      this.theme = theme === 'dark' ? 'dark' : 'light';
      document.documentElement.classList.toggle('ion-palette-dark', theme === 'dark');
    }
    

    Here is my hrml for toggle dark and light theme

    <ion-menu-toggle auto-hide="false">
      <ion-item lines="none" detail="false" (click)="toggleTheme()">
        <ion-icon aria-hidden="true" slot="start" [name]="theme === 'dark' ? 'sunny' : 'moon'"></ion-icon>
        <ion-label>{{ theme === 'dark' ? 'Light': 'Dark' }} Mode</ion-label>
      </ion-item>
    </ion-menu-toggle>