Ravi Gaud
Ravi Gaud

Reputation: 523

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.

Upvotes: 0

Views: 586

Answers (2)

Ravi Gaud
Ravi Gaud

Reputation: 523

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>

Upvotes: 1

Najam Us Saqib
Najam Us Saqib

Reputation: 3402

To make it conditional make below mentioned changes:

1). comment all thee of these in your global.scss:

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

2). Go to your theme/variable.scss

Take everything out of @media (prefers-color-scheme: dark) media query and pase it out side (simply comment media query open and close tag).

3). On the basis of your condition you can toggle dark mode on and off:

changeDarkMode(darkodetype: boolean){
   document.body.classList.toggle('dark', darkModetype);
}

Note: Disableing dark mode media query will always shows light mode. you have to enable dark mode programatically.

Upvotes: 0

Related Questions