Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set background color for a div dynamically in angular? [duplicate]

Tags:

angularjs

I'm very new to angular. I'm getting the background color to be shown from a backend api. I want to set it as a div's background color:

I've tried:

<div style="background-color: {{vitalItem.value.color}}" >

but the color is not set. In console, it shows:

WARNING: sanitizing unsafe style value background-color: #d9534f (see http://g.co/ng/security#xss)

Any help is appreciated..

EDIT:

Here's my html

<div class="latest-reading-box">
     <div class="latest-reading-container value-contain-type" ng-style="{'background-color': vitalItem.value.color}">
         <p class="p-time">{{vitalItem.value != null ? vitalItem.value.date : ""}}</p>
         <h3 class="latest-value">{{vitalItem.value != null ? vitalItem.value.value : ""}}</h3>
         <p class="type-value">{{vitalItem.value != null && vitalItem.value.vitalEntryType != 0 ?
                                                  getVitalEntryTypeName(vitalItem.value.vitalEntryType): ""}}</p>
     </div>
</div>

In chrome's inspect, this is what see:

<div _ngcontent-c1="" class="latest-reading-container value-contain-type" ng-style="{'background-color': vitalItem.value.color}">
    <p _ngcontent-c1="" class="p-time">08 Jul, 2017</p>
    <h3 _ngcontent-c1="" class="latest-value">67</h3>
    <p _ngcontent-c1="" class="type-value"></p>
</div>

everything except vitalItem.value.color is showing their value. Why is ng-style not working?

like image 937
Drunken Daddy Avatar asked Jul 11 '17 09:07

Drunken Daddy


People also ask

How do I change the color of a dynamic div?

To achieve this, you must set the --backcol within the var function as the value of the body background-color. var inputcolor = document. getElementById("favcolor"); var root = document.

Can you put a background color for a div?

To set a background color for a div or related element in CSS, you use the background-color property. While setting this background color, your creativity is your limit as to how far you want to go.

Can we update background color of div HTML tag using NgStyle?

The NgStyle directive lets you set a given DOM elements style properties. This sets the background color of the div to green.

What is the default background color of a div?

The default background color of a div is transparent . So if you do not specify the background-color of a div, it will display that of its parent element.


1 Answers

You can use ng-style to achieve this

<div ng-style="{'background-color':vitalItem.value.color}" >
like image 173
Vivz Avatar answered Nov 15 '22 04:11

Vivz