Ionic 2 & 3 Dynamically switching themes
2 min readJul 4, 2018
First of all create two files in the project’s /theme
director :
├── /src
└── /theme
...
├── red-theme.scss
├── blue-theme.scss
.blue-theme {
ion-content {
background: #00b4db;
background: -webkit-linear-gradient(to right, #00b4db, #0083b0);
background: linear-gradient(to right, #00b4db, #0083b0);
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
}
}
.red-theme {
ion-content {
background: #ed213a;
background: -webkit-linear-gradient(to right, #ed213a, #93291e);
background: linear-gradient(to right, #ed213a, #93291e);
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
}
}
In your variable.scss file import these two scss:
// App Theme
// --------------------------------------------------
@import "ionic.theme.default";
@import "./red-theme";
@import "./blue-theme";
We are done with two separate scss files.Now we will add toggle button on home screen which will toggle themes.
...
<ion-content padding>
...
<button ion-button full icon-left (click)="changeTheme()">
<ion-icon name="color-palette"></ion-icon>
Change Theme
</button>
</ion-content>
Now we have to update home.ts file
import { Component } from '@angular/core';
import { NavController, Events } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,
public event: Events) {
}
changeTheme() {
this.event.publish('theme:toggle');
}
}
When the changeTheme()
method is invoked a theme:toggle
event is published.
Now in your myApp.ts we need to subscribe this event
export class MyApp {
rootPage:any = HomePage;
theme:String = 'blue-theme';//keep default theme as blue
constructor(public platform: Platform,
public event: Events) {
platform.ready().then(() => {
if(localStorage.getItem(“activeTheme” === null){
localStorage.setItem(“activeTheme”, this.theme);
}else{
this.theme = localStorage.getItem(“activeTheme”);
}
event.subscribe('theme:toggle', () => {
this.toggleTheme();
});
});
}
toggleTheme() {
if (this.theme === 'blue-theme') {
this.theme = 'red-theme';
} else {
this.theme = 'blue-theme';
}
localStorage.setItem(“activeTheme”, this.theme); }
}
we also need to update app.html
<ion-nav [root]="rootPage" [class]="theme"></ion-nav>
If you want to apply theme for slide menu then add ion-menu class to theme in app.html
<ion-menu [content]=”content” [class]=”theme”>
Cheers!! We are Done! Have any query ask me!
Thanks & Regards,
Mahesh Bhusanoor