How to change the color of a div in code dynamically in ionic by using code?
1 Answer
If it's just a single style, you can use property binding for this. In your component:
public aColor: string = "#ccc";
And then in the view:
<div [style.background-color]="aColor"></div>
Please take a look at the ngStyle docs for more info if you need to set more than one style dynamically:
<some-element [ngStyle]="{'font-style': styleExp}">...</some-element>
<some-element [ngStyle]="{'max-width.px': widthExp}">...</some-element>
<some-element [ngStyle]="objExp">...</some-element>
4 Comments
sebaferreras
Glad to help!. Please keep in mind that Ionic2/3 works on top of Angular ,so you can always find how to do these kind of things in Angular docs :)
Albert-Jan
I didn't realize, sorry. Thank you very much :)
Albert-Jan
this doesn't allow me to change it on runtime, only when the page is initiated, because when I update the variable afterwards, it doesn't change its color. Thanks in advance :)
sebaferreras
Yes, since it's property binding, this should change the color every time that the
aColor property is updated in the component code. If that doesn't happen on your end, then maybe there's an issue related to how and when Angular detects the changes. If you want, please create a new question (since it wouldn't be related to this one) so we can take a look at it and see what could be going on...