How to set color in div element using property binding with Angular 4

3.9k Views Asked by At

I have the follow object

 public countries= [
    {code: 'AE' , country_name: 'United Arab Emirates', color: '#eea638'},
    {code: 'AF' , country_name: 'Afghanistan', color: '#eea638'},
    {code: 'AL' , country_name: 'Albania', color: '#eea638'},
    {code: 'AM' , country_name: 'Armenia', color: '#eea638'},
    {code: 'US' , country_name: 'United State',color: '#eea638'},
    {code: 'AR' , country_name: 'Argentina', color: '#eea638'},
    {code: 'AT',  country_name: 'Austria', color: '#eea638'},
    {code: 'AU',  country_name: 'Australia', color: '#eea638'}
]

So I would like to set the div color dinamically based in this object list. I tried to do this:

<div *ngFor="let country of countries">
    <p class="m-b-10">{{country.country_name}} 
        <span class="f-right">{{country.code}}</span>
    </p>
    <div class="progress">
        <div class="progress-bar" ng-style="{'background-color': country.color}" [style.width]="'75%'"></div>
   </div>

But it's not working. Could you please help me?

2

There are 2 best solutions below

0
On BEST ANSWER

There are two issues with your implementation:

  1. You've used ng-style which was used in AngularJS(1.x). But since you're working with Angular(2+) use [ngStyle] instead of ng-style.

  2. Your div doesn't have a content. Also, it just has width and not height. Another thing to point out here is that since you're using [ngStyle], you can use the width and the height attributes right there instead of creating another [style.width] or [style.height] attribute binding.


Give this a try to fix it:

<div *ngFor="let country of countries">
  <p class="m-b-10">{{country.country_name}}
    <span class="f-right">{{country.code}}</span>
  </p>
  <div class="progress">
    <div 
      class="progress-bar" 
      [ngStyle]="{ 'background-color': country.color, 'width': '75%', 'height': '50px'}">
    </div>
  </div>
</div>

Here's a Sample StackBlitz for your ref.

0
On

Div height is missing.

   <div class="progress">
        <div class="progress-bar" [ngStyle]="{'background-color': country.color}" style="width:75%; height:25px" ></div>
   </div>