简体   繁体   中英

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 -

图片

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM