Set background-color from an array of colors

2

I have a component that is responsible for displaying the values of an array of objects and each object has a series of colors assigned:

colores: any = [
    {id: 1, c1: '#f0f0f0', c2: '#c8c8c8', c3: '#b4b4b4', c4: 'a0a0a0', c5: '8c8c8c'},
    {id: 2, c1: '#ff0ff', c2: '#ee82ee', c3: '#da70d6', c4: 'ba55d3', c5: '9370db'}
];

Using the * ngFor directive I am trying to show the colors but not as text, but as the color itself, setting it as the background of a div (in the following code the text of each color would come out) :

<div *ngFor="let color of colores">
  <div>{{color.c1}}</div>
  <div>{{color.c2}}</div>
  <div>{{color.c3}}</div>
  <div>{{color.c4}}</div>
  <div>{{color.c5}}</div>
  <hr>
</div>

And I'm trying to pass the properties of the object directly as a style and I see that it does not work:

<div *ngFor="let color of colores">
  <div style="background: {{color.c1}}">{{color.c1}}</div>
  <div style="background: {{color.c2}}">{{color.c2}}</div>
  <div style="background: {{color.c3}}">{{color.c3}}</div>
  <div style="background: {{color.c4}}">{{color.c4}}</div>
  <div style="background: {{color.c5}}">{{color.c5}}</div>
  <hr>
</div>

How can I do this correctly?

    
asked by gmarsi 30.12.2017 в 18:57
source

2 answers

2

To make the binding of a style you can use the following syntax:

  <div [style.propiedad-css]="valor"></div>

For your example it would be the following:

  <div [style.background-color]="color.c1">{{color.c1}}</div>

Here I leave you an example working.

  

NOTE: Notice that in the definition of the Array of colors, in some   cases you forgot to put the%% pad% before the code   hexadecimal color.

    
answered by 30.12.2017 / 19:10
source
2

You have to bin it with the ngStyle directive.

<div [style.background]="color.c1">{{ color.c1 }}</div>
    
answered by 30.12.2017 в 19:10