0

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.

Paul Floyd
  • 5,530
  • 5
  • 29
  • 43
jxStackOverflow
  • 328
  • 1
  • 7
  • 17
  • 2
    Possible duplicate of [Generate dynamic css based on variables angular](https://stackoverflow.com/questions/46047502/generate-dynamic-css-based-on-variables-angular) – Prashant Pimpale Jul 11 '19 at 07:09

6 Answers6

5

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' }"
לבני מלכה
  • 15,925
  • 2
  • 23
  • 47
0

Try like this:

<div [style.background-color]="cardData.color" style="padding: 10px 20px;"></div>
Adrita Sharma
  • 21,581
  • 10
  • 69
  • 79
0

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

<div  [ngStyle]="{'background-color': cardData.color}">...</div >
nitoloz
  • 165
  • 1
  • 16
0

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

<div [ngStyle]="{'background-color': cardData.color, 'padding': '10px 20px'}">Some Content</div>
Ganesh
  • 5,808
  • 2
  • 21
  • 41
valik
  • 26
  • 3
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>
Sreejith Ms
  • 105
  • 6
0

below code snippet has worked for me

<div [ngStyle]="{'background-color':cardData.color}"></div>
Rohan Patil
  • 175
  • 1
  • 4