动态样式在 Angular2 中不起作用
Dynamic styling not working in Angular2
以下是我的工作代码,它没有在控制台中给出任何错误并按预期打印数组项和测试标题。但是不知何故动态背景样式不起作用,让我知道我在这里做错了什么。
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'];
}
以下是我得到的输出 -
不鼓励直接绑定到 style
(并非在所有浏览器上都适用)。改用
<div class="one" *ngFor="let item of colArr" [ngStyle]="{background: item}">{{item}}</div>
或
<div class="one" *ngFor="let item of colArr" [style.background]="item">{{item}}</div>
以下是我的工作代码,它没有在控制台中给出任何错误并按预期打印数组项和测试标题。但是不知何故动态背景样式不起作用,让我知道我在这里做错了什么。
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'];
}
以下是我得到的输出 -
不鼓励直接绑定到 style
(并非在所有浏览器上都适用)。改用
<div class="one" *ngFor="let item of colArr" [ngStyle]="{background: item}">{{item}}</div>
或
<div class="one" *ngFor="let item of colArr" [style.background]="item">{{item}}</div>