Ionic Native APP Dark and light mode theme - change dynamically

Ionic Native APP  Dark and light mode theme - change dynamically

Creating an Ionic app

lets create an ionic application with a blank template based on the angular framework.

Open cmd and enter ionic start [app name] blank --cordova, it will ask which framework you liked to work, here we have created a project on the angular framework.

It will take some time to create an ionic project once it’s done open the newly created ionic app in VS code.

Install Ionic Storage

we will use ionic storage to store our theme setting so that even if the user closes our application and reopen it the theme setting will remain the same without losing the user theme setting.

Open the terminal in VS code and enter npm install --save @ionic/storage to Install ionic storage 

If using angular instead install npm install @ionic/storage-angular

Update App Module

Once npm installation is complete, we need to update the app.module.ts like below

Import the ionicStorageModule and add an entry inside @NgModule import


import { NgModule } from "@angular/core";
import { BrowserModule } from "@angular/platform-browser";
import { RouteReuseStrategy } from "@angular/router";

import { IonicModule, IonicRouteStrategy } from "@ionic/angular";

import { AppComponent } from "./app.component";
import { AppRoutingModule } from "./app-routing.module";

import { IonicStorageModule } from "@ionic/storage-angular";

@NgModule({
  declarations: [AppComponent],
  entryComponents: [],
  imports: [
    BrowserModule,
    IonicModule.forRoot(),
    AppRoutingModule,
    IonicStorageModule.forRoot(),
  ],
  providers: [{ provide: RouteReuseStrategy, useClass: IonicRouteStrategy }],
  bootstrap: [AppComponent],
})
export class AppModule {}


Adding Dark mode SCSS

Go to https://ionicframework.com/docs/theming/dark-mode#ionic-dark-theme and copy the dark mode SCSS values.

Open the variables.scss file and paste the copied value at the bottom.

Create Theme Service

Let’s create a service to store and retrieve our app theme setting. Open an terminal in VS Code and enter the command ionic g service service\theme.

It will create a ThemeService class inside the service folder. In the below code we added a constant (a unique identifier) which is used to store and identify our theme setting in storage.

The changeAppTheme method takes a theme value (argument).

  • If the passed argument is dark then add dark class to the body and remove light class.
  • If the passed argument is light then add light class to the body and remove dark class.

The storage.set() method takes two arguments, the first argument is the unique identifier and the second argument is the value to store.


import { Injectable } from '@angular/core';
import { Storage } from '@ionic/storage-angular';

const CURRENTTHEME = 'appTheme';

@Injectable({
  providedIn: 'root',
})
export class ThemeService {
  
  darkValue: any;
  private _storage: Storage | null = null;

  constructor(private storage: Storage) {
    this.init();
  }

  async init() {
    this._storage = await this.storage.create();
  }

  changeAppTheme(dark) {
    if (dark === 'dark') {
      this.darkValue = true;
      document.body.classList.add('dark');
      document.body.classList.remove('light');
    } else {
      this.darkValue = false;
      document.body.classList.remove('dark');
      document.body.classList.add('light');
    }
    this._storage.set(CURRENTTHEME, dark);
    return this.darkValue;
  }
}

Now our service class is ready we can use it anywhere in our app.

Create Dark mode toggle

Open the home page and add the below code, we have added the mode toggle(dark and light mode) button in the header toolbar.

We have two buttons to toggle between light and dark mode and a boolean variable to show one button corresponding to the current mode.

If the current mode is dark then the light mode switch button is shown the same as if the mode is light then the dark mode switch button is shown.


<ion-header [translucent]="true">
  <ion-toolbar>
    <ion-title>
      Blank
    </ion-title>
    <ion-buttons slot="end">
      <ion-button *ngIf="!darkValue" (click)="changeTheme('dark')">
          <ion-icon name="moon-outline"></ion-icon>
      </ion-button>
      <ion-button *ngIf="darkValue" (click)="changeTheme('white')">
          <ion-icon name="sunny-outline"></ion-icon>
      </ion-button>
  </ion-buttons>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-header collapse="condense">
    <ion-toolbar>
      <ion-title size="large">Blank</ion-title>
    </ion-toolbar>
  </ion-header>

  <div id="container">
    <strong>Ready to create an app?</strong>
    <p>Start with Ionic <a target="_blank" rel="noopener noreferrer" href="https://ionicframework.com/docs/components">UI Components</a></p>
  </div>
</ion-content>

Now we have our HTML page over.

Let's update the typescript part now, open the home page.ts file and import our ThemeService class and create the ChangeTheme method which updates app theme setting in ionic storage.


import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { ThemeService } from '../service/theme.service';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  darkValue: any;
  notes: any[];

  constructor(private themeService: ThemeService,
    private router: Router
    ) {}

  get darkBoolean() {
    return this.themeService.darkValue;
  }

  async ngOnInit() {
    this.darkValue = this.darkBoolean();
    await this.themeService.init();
  }

  changeTheme(event: any) {
    this.themeService.changeAppTheme(event);
    this.darkValue = this.themeService.darkValue;
  }
}

Run the App

Since we have done all things to toggle dark and light mode let's run our app and see.

Open the terminal and enter ionic serve to start our application.

Once the application is started, you can see a new tab is opened in the browser or you can open the application at http://localhost:8100 URL.

ionic 4 native app dark mode home screen


Change the mode and see whether the theme setting is saving in storage or not.

To check the app storage right → inspect → application, you will see all storage click on the indexed DB.

ionic 4 native app storage for dark mode


We have successfully saved data in storage but if we close our application and reopen it theme setting is not coming instead default white mode is coming so in order to make our app start by the user preference (value stored in storage).

we need to make small changes to our app.component.ts file so when our app starts we get the theme setting saved in storage and apply them.


import { Component } from '@angular/core';
import { Storage } from '@ionic/storage';
import { ThemeService } from './service/theme.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss'],
})
export class AppComponent {

  constructor(private themeService: ThemeService,
    private storage: Storage) {
    this.storage.get('appTheme').then((mode) => {
      this.themeService.changeAppTheme(mode);
    });
  }
}

Our app looks like below after all the changes.

Ionic Native APP  Dark and light mode theme - change dynamically using ionic storage sample

Learn how to apply for google Admob for app monetization and show ads in ionic app

Post a Comment

Previous Post Next Post

Recent Posts

Facebook