3

How to change the color of a div in code dynamically in ionic by using code?

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

4 Comments

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 :)
I didn't realize, sorry. Thank you very much :)
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 :)
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.