简体   繁体   中英

Ionic 5 Dynamically change primary color

I am trying to make my Ionic Angular app's color scheme change based on events that happen while using the app. The app is quite large with many components that all need to be aware of the color change when it happens. Ideally I would like to know of a way to have my elements reference a color(s) (let's say --primary) and to be able to change that color in one place and have all the elements respond to the change.

I have not found anything in the Ionic docs that references being able to change the CSS variable definitions at runtime so I have looked at instead swapping which variable I use at runtime.

I have considered listing many different colors in the variables.scss and then using ngClass to apply a globally defined class name that can respond to the change. The downside of this is I would have to anticipate and individually declare each possible attribute that needs the color. For example, I could use [ngClass]="primary-1" to apply a class defined like this:

.primary-1 {
background: var(--ion-color-primary-1);
}

but if I wanted to use an element that needed the background-color attribute I would also need a different class for that attribute:

.primary-1-other {
background-color: var(--ion-color-primary-1) 
}

My problem is that I do not want the global class definitions to be aware of the specific element attributes unless there is a concise and comprehensive way to do that.

I have also looked into using setProperty but as far as I can tell that only changes styles in the specific context rather than the app as a whole.

Any solutions/ideas are appreciated.

I think what you want is to modify Ionic's Global CSS Variables. They are a bunch of runtime modifiable variables. You're in luck, because in the old days, you could only modify those variables at compile time. Now, there are methods to modify at runtime.

This guide explains how: https://ionicframework.com/docs/theming/css-variables

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM