Ionic comes with a variables.scss file, and in there you can set up different style variables such as primary colours, etc.
Is there a way I can programmatically change variables inside of here?
$colors: (
primary: #ffbb00,
secondary: #32db64,
danger: #f53d3d
);
For example: changing the primary color to the result of a color picker
So i got curious and was looking around to see if i was able to find a solution, so here's what i got:
You can't change the SASS variable since it's compiled and turned into css, so any tag you use an attribute color="your Color Name"
will be pre-processed in the build process and turned into lots of background-color
and other stuff.
So i started to look for using css variables with the SASS variable, something like
:root {
--modified-color: #333;
}
/*Declaring it here \/ or inside :root */
$colors: (
primary: --modified-color,
secondary: #32db64,
danger: #f53d3d
);
But wasn't able to achieve what i wanted, or i don't know how to do it properly. With a variable maybe you could do what's in my next idea, but in a easier way.
So i thought "maybe there's a workaround" and something came to my mind:
- You could create a class, let's call it
.dynamic-bg-color
.
- Initially set it to a color you want, let's say
.dynamic-bg-color: { bakcground-color: #333}
.
- Give that class to any component you want to change, like
<ion-item>
or <ion-toolbar>
or <button>
.
- Save this color as a string in somewhere, like a localStorage, NativeStorage, etc. (
this.storage.set('dynamic', '#333')
);
When the user pick a new color, you'll override the old color in the storage and change color for your class:
public updateColor = (pickedColor) => {
const color: string = pickedColor; // I'M ASSUMING THE PICKER RETURNS IT AS A STRING LIKE '#333333'
let myTags = document.getElementsByClassName('dynamic-bg-color');
for(i=0; i < myTags.length; i++) {
myTags [i].style.backgroundColor = color;
// UPDATE ANYTHING ELSE YOU WANT
}
}
Probably you'll need to update everytime you enter a new page, since it'll generate newer tags with that class, so put a code on ionViewWillEnter so everytime he goes on or back to that page it updated the color.
Haven't tried this, but it's worth a shot. If you try this let me know if it worked.
Hope this helps :D