Implement Dark & Light Mode to your Ionic 4 Apps

12
SHARES
544
VIEWS

In the previous article we have implemented Dark and Light Mode in our ionic 3 App. And Now we are going to add Dark and Light Mode into our ionic 4 App. In this article, you’ll learn how you can add Dark & Light mode in your ionic 4 applications. This feature is very important and nearly every app needs this kind of functionality. Remember we are using Ionic 4 for this specific project and for exact results I suggest you should the same Ionic version.

Setup Your App

Create a new ionic 4 Project with the following command:

$ ionic start dark_and_light_mode_ionic_app sidemenu

Go into your Project Diratory.

$ cd dark_and_light_mode_ionic_app

Generate a new service with the following command:

$ ionic g service theme

Open /src/app/theme.service.ts file and add the following Code

import { Injectable, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
import { DomController } from '@ionic/angular';

interface Theme {
  name: string;
  styles: ThemeStyle[];
}

interface ThemeStyle {
  themeVariable: string;
  value: string;
}

@Injectable({
  providedIn: 'root'
})
export class ThemeService {

  private themes: Theme[] = [];
  public currentTheme = 0;

  constructor(private domCtrl: DomController, @Inject(DOCUMENT) private document) {
    this.themes = [
      {
        name: 'day',
        styles: [
          { themeVariable: '--ion-color-primary', value: '#3880ff'},
          { themeVariable: '--ion-background-color', value: '#ffffff'},
          { themeVariable: '--whiteColor', value: '#ffffff'},
          { themeVariable: '--darkToLight', value: '#222222'},
          { themeVariable: '--lightToDark', value: '#ffffff'},
          { themeVariable: '--grey', value: '#eeeeee'},

        ]
      },
      {
        name: 'night',
        styles: [
          { themeVariable: '--ion-color-primary', value: '#222428'},
          { themeVariable: '--ion-color-primary-rgb', value: '34,34,34'},
          { themeVariable: '--ion-color-primary-contrast', value: '#ffffff'},
          { themeVariable: '--ion-color-primary-contrast-rgb', value: '255,255,255'},
          { themeVariable: '--ion-color-primary-shade', value: '#1e2023'},
          { themeVariable: '--ion-color-primary-tint', value: '#383a3e'},
          { themeVariable: '--ion-item-ios-background-color', value: '#717171'},
          { themeVariable: '--ion-item-md-background-color', value: '#717171'},
          { themeVariable: '--ion-tabbar-background-color', value: '#222428'},
          { themeVariable: '--ion-tabbar-ios-text-color-active', value: '#ffffff'},
          { themeVariable: '--ion-tabbar-md-text-color-active', value: '#ffffff'},
          { themeVariable: '--ion-background-color', value: '#383838'},
          { themeVariable: '--darkToLight', value: '#ffffff'},
          { themeVariable: '--lightToDark', value: '#222222'},
          { themeVariable: '--grey', value: '#333333'},

        ]
      }
    ]
  }

  setTheme(name): void {
    let theme = this.themes.find(theme => theme.name === name);
    this.domCtrl.write(() => {
      theme.styles.forEach(style => {
        document.documentElement.style.setProperty(style.themeVariable, style.value);
      });

    });

  }
}

Now open /src/app/app.component.ts file and add the following code:

import { Component } from '@angular/core';

import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import {ThemeService } from './theme.service';

@Component({
  selector: 'app-root',
  templateUrl: 'app.component.html',
  styleUrls: ['app.component.scss']
})
export class AppComponent {
  public appPages = [
    {
      title: 'Home',
      url: '/home',
      icon: 'home'
    },
    {
      title: 'List',
      url: '/list',
      icon: 'list'
    }
  ];

  constructor(
    private platform: Platform,
    private splashScreen: SplashScreen,
    private statusBar: StatusBar,
    private themeSwitcher: ThemeService
  ) {
    this.initializeApp();
  }

  initializeApp() {
    this.platform.ready().then(() => {
      this.statusBar.styleDefault();
      this.splashScreen.hide();
    });
  }

  ThemeSwitcher() {
    // 0 = day mode
    // 1 = night mode
    if (this.themeSwitcher.currentTheme === 0) {
      this.themeSwitcher.setTheme('night');
      this.themeSwitcher.currentTheme = 1;
    } else {
      this.themeSwitcher.setTheme('day');
      this.themeSwitcher.currentTheme = 0;
    }
  }
}

Create a new theme.scss file in src/app/ diractory and add the following code:

:root {
  --whiteColor : #ffffff;
  --lightToDark: #ffffff;
  --darkToLight: #222222;
  --blueColor: #4da3ff;
  --grey: #eeeeee;
}

Open /src/app/app.component.scss file and add the following code:

@import url(./theme.scss);
p,
ion-label,
ion-item,
ion-icon,
ion-title,
button {
  color: var(--darkToLight) !important;
}

Open /src/app/home/home.page.scss and put the following code:

@import url(../theme.scss);

.welcome-card img {
  max-height: 35vh;
  overflow: hidden;
}

p,
ion-card-subtitle,
ion-card-title,
ion-label,
ion-item,
ion-title,
button {
  color: var(--darkToLight) !important;
}

Open /src/app/app.component.html and add ThemeSwitcher button anywhere you want. My /src/app/app.component.html file look like this:

<ion-app>
  <ion-split-pane contentId="main-content">
    <ion-menu contentId="main-content" type="overlay">
      <ion-header>
        <ion-toolbar>
          <ion-title>Menu</ion-title>
        </ion-toolbar>
      </ion-header>
      <ion-content>
        <ion-list>
          <ion-menu-toggle auto-hide="false" *ngFor="let p of appPages">
            <ion-item [routerDirection]="'root'" [routerLink]="[p.url]">
              <ion-icon slot="start" [name]="p.icon"></ion-icon>
              <ion-label>
                {{p.title}}
              </ion-label>
            </ion-item>
          </ion-menu-toggle>

          <ion-item (click)="ThemeSwitcher()">
            <ion-icon slot="start" name="bulb"></ion-icon>
            <ion-label>
              Dark/Light Mode
            </ion-label>
          </ion-item>
        </ion-list>
      </ion-content>
    </ion-menu>
    <ion-router-outlet id="main-content"></ion-router-outlet>
  </ion-split-pane>
</ion-app>

Now when we Tap the Dark/Light Mode ionic change the current theme.

Finaly our ionic 4 app look like this:

Light Mode
Dark Mode

Github Repository: https://github.com/mubeenkhan246/dark_and_light_mode_ionic_app

How to add Dark & Light Mode to your Ionic 3 App

Best Resource to learn ionic 4, Firebase and Angular

Muhammad Mubeen

Muhammad Mubeen

Mubeen is a full-stack web & mobile app developer who is very proficient in MEAN.js, Vue, Python, Ionic 4, Flutter, Firebase, ROR, and PHP. He has created multiple mobile and web applications. He is very passionate about sharing his knowledge.

Comments 4

  1. ion Bar says:

    I love this informative content. Thanks.

  2. Tagi Asadullazadeh says:

    Very useful. Thanks 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *