简体   繁体   English

动态样式在Angular2中不起作用

[英]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). 不建议直接绑定到style (并非在所有浏览器上都很好用)。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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