I posted this on the Ionic forum, but I never seem to have luck on their forums, so I thought I'd try here.
I'd like to have options for a "dark" and "light" theme that a user can choose in their settings. What's the best way to go about that? Can I programmatically switch between ionic themes, like dark and stable?
Thanks in advance.
The fastest way to change the theme of your Ionic app is to set a new value for primary , since Ionic uses the primary color by default to style most components. Colors can be removed from the map if they aren't being used, but primary should not be removed.
One way to remove the dark theme would be by editing the variables. scss file and removing this style rule: @media (prefers-color-scheme: dark) { ... } That media query is the one that changes all the colors of the CSS custom properties when the users selects the dark theme on the device.
Ionic Dark Theme Ionic has a recommended theme for variables to use in order to get a dark mode based on the device running the app. It can be broken down into the following parts: Changing the default Ionic colors for all modes to complement the dark background in the body. dark selector.
You can you ng-style to pass a css options object to an element. This will toggle font color on the element. Following this pattern you would have dark and light theme objects that you toggle between.
<div ng-style="style" class="item">
This is a basic Card.
<button ng-click="toggle()">Toggle</button>
</div>
And in your controller
.controller('AppCtrl', function($scope) {
$scope.style = {
color: '#000'
};
$scope.toggle = function() {
$scope.style.color = ($scope.style.color === '#000' ? '#fff' : '#000');
};
});
Demo
Here is a simple example where you want to change the color of your header dynamically:
<ion-header-bar ng-class="'bar-' + appTheme">
<h1 class="title">Ionic - Switch Themes</h1>
</ion-header-bar>
In your controller:
var selectedTheme = $window.localStorage.appTheme;
if (selectedTheme) {
$scope.appTheme = selectedTheme;
} else {
$scope.appTheme = 'positive';
}
$scope.themeChange = function (theme) {
// save theme locally
$window.localStorage.appTheme = theme;
// reload
$window.location = '';
}
Live demo and full example @: http://techiedreams.com/ionic-custom-and-dynamic-theming/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With