How to set background-color by angular bound value

2019-08-27 13:18发布

问题:

I have a simple angular app (version 4.2.6) that displays tiles. I want to set the background color of those tiles by a value bound to tile object. While setting the content of the tile works as expected, setting the color fails:

<div *ngFor="let tile of tiles" class="col-md-3 col-sm-6 col-xs-12" >
    <div style="border-style: solid;width: 150px;height: 150px;background-color:{{tile.color}};" class="tile">{{tile.name}}</div>
</div>

How to set background-color by bound value tile.color (it contains color as hex string )?

回答1:

You can use [style.backgroundColor]="tile.color"

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


回答2:

use the ngStyle directive

<div [ngStyle]="{'background-color':tile.color}" style="border-style: solid;width: 150px;height: 150px;" class="tile">{{tile.name}}</div>


标签: css angular