Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically set scss variables angular ionic

I have an API call that would get a json with my scss colours, such as

dynamic-colour: #5260ff

but this variable doesn't get called until run time of the ionic app. Was setting scss variables dynamically before compile time even possible?

From most of the angular examples I've seen, they already have a preset colour set, and I don't see any examples of what I want to achieve. Is it possible to preset a variable, but override it when running the app?

Anyone know anyways to accomplish dynamically getting scss variables from an API call and setting global variable values? I believe it's possible to run a typescript function to override each page's scss with what I want.

like image 725
NeedHelp101 Avatar asked Mar 10 '20 06:03

NeedHelp101


1 Answers

SCSS is compiled to CSS during compile time, and SCSS variables are replaced with resolved value during compile time, which means there is no way to change the variable during run time. However css variables just sits there and you can easily change them,

for instance:

:root{
   --dynamic-colour: #5260ff
}

now you can change its value from your component like:

changeColor(color:string){
   document.documentElement.style.setProperty('--dynamic-colour', color);
}

Also you can assign --dynamic-colour to your scss variable as well so you wont have to do change in multiple places:

$dynamic-colour: var(--dynamic-colour);

STACKBLITZ WORKING DEMO

like image 156
Mustahsan Avatar answered Nov 16 '22 05:11

Mustahsan