Tech Solvr Tech Solvr - 6 months ago 61
CSS Question

Dynamic styling not working in Angular2

Following is my working code, which is not giving any error in console and printing the array items and test heading as expected. BUT somehow dynamic background styling in not working, Let me know what I am doing wrong here.

import { Component } from '@angular/core';

@Component({
selector: 'my-app',
template: `
<h1>{{name}}</h1>
<div class="one" *ngFor="let item of colArr" style="background: {{item}};">{{item}}</div>
`,
styles: [`
.one {
width: 100%;
text-align: center;
padding: 10px;
margin: 5px;
}
`]
})

export class HomeComponent {
public name = 'test';
public colArr = ['#111111', '#222222', '#333333', '#444444', '#555555', '#666666', '#777777', '#888888', '#999999'];
}


Following is the output I am getting -

image

Answer

Direct binding to style is discouraged (doesn't work well on all browsers). Use instead

<div class="one" *ngFor="let item of colArr" [ngStyle]="{background: item}">{{item}}</div>

or

<div class="one" *ngFor="let item of colArr" [style.background]="item">{{item}}</div>