1

I am working on Angular and is trying to set this div background color dynamically based on the color specified by "cardData.color".

E.g.

cardData = {id: '1', color: '#202020'};

I've tried the code shown below but it doesn't work.

<div style="background-color: {{cardData.color}}; padding: 10px 20px;"></div>

Is there any way, I can set the background color dynamically based on the object's color?? Thank you.

1

6 Answers 6

6

Use [] to get the value of cardData.color without {{}} also you can use style.backgroundColor.

<div [style.backgroundColor]="cardData.color" style="padding: 10px 20px;"></div>

Another way to do it:

[ngStyle]="{'background-color': cardData.color , 'padding': '10px 20px' }"
Sign up to request clarification or add additional context in comments.

Comments

0

Try like this:

<div [style.background-color]="cardData.color" style="padding: 10px 20px;"></div>

1 Comment

backgroundColor no background-color!!
0

Following angular style guide I would recommend to use [ngStyle]:

<div  [ngStyle]="{'background-color': cardData.color}">...</div >

Comments

0

You can use both ngStyle and style bindings

For: Style Binging

<div [style.backgroundColor] = "cardData.color"></div>

And For: ngStyle Binding

 <div [ngStyle] = "{ backgroundColor: cardData.color}"></div>

Comments

0

Use [ngStyle] to have access to variables from the component.

<div [ngStyle]="{'background-color': cardData.color, 'padding': '10px 20px'}">Some Content</div>

Comments

0

below code snippet has worked for me

<div [ngStyle]="{'background-color':cardData.color}"></div>

Comments

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.