Change Ionic Theme Dynamically
- Fire Focus
- Jan 5, 2021
- 2 min read
Introduction
In this section, I'll show you how you can change your theme in ionic app dynamically.More specifically we'll change only the --ion-primary-color.
The Code
I have an array with name and color of the theme.A method to change the theme dynamically.Very simple, we only apply style property for the documentElement ie., the app.
theme.page.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-theme', templateUrl: './theme.page.html', styleUrls: ['./theme.page.scss'], }) export class ThemePage implements OnInit { colorThemes: Array<any> = [ { name: "Red", color: "#ce4e57" }, { name: "Green", color: "#41b05d" }, { name: "Yellow", color: "#d3ae40" }, { name: "Blue", color: "#3490eb" }, { name: "Pink", color: "#cd5f93" }, { name: "Orange", color: "#d28036" }]; setTheme(color) { document.documentElement.style.setProperty("--ion-color-primary", color); } constructor() { } ngOnInit() { } } The Markup
Very simple UI with a header section and a form and bottom of this a ngFor to display the colorThemes array.
theme.page.html
<ion-content> <div id="header"> <img src="/assets/logo.jpg" id="logo" alt=""> <h1>Fire Focus</h1> </div> <ion-card mode="ios"> <div class="form"> <ion-item mode="md"> <ion-label position="floating">Phone Number</ion-label> <ion-input></ion-input> </ion-item> <ion-button expand="block" mode="md"> <b>Login with phone number</b> </ion-button> </div> <div class="container"> <div class="inner" *ngFor="let colorTheme of colorThemes" (click)="setTheme(colorTheme.color)"> <div class="color" [style.background]="colorTheme.color"> </div> <br> {{colorTheme.name}} </div> </div> </ion-card> </ion-content>
And The CSS...
Css for the HTML file is below
theme.page.scss
#header { position: fixed; height: 50%; width: 100%; background: var(--ion-color-primary); #logo { width: 100px; border-radius: 100%; position: absolute; left: 50%; transform: translate(-50%, 50px); } h1 { border-radius: 100%; position: absolute; left: 50%; transform: translate(-50%, 140px); color: #fff; letter-spacing: 1px; } } ion-card { position: fixed; top: 40%; width: 100%; padding: 16px; margin: 0 auto; height: 100%; border-radius: 30px; } .form { margin: 0 auto; width: 50%; ion-button { --box-shadow: 0; margin-top: 20px; } } .container { margin-top: 50px; text-align: center; .inner{ display: inline-block; } .color { display: inline-block; width: 100px; height: 100px; border-radius: 100%; margin: 10px; cursor: pointer; transition: 0.3s; } .color:hover { border: 10px solid #ffffff; } }
Thats it! Hope it helps..Thanks for reading.Cheers!!!
Comments