Angular2组件 - 动态内联样式

Awe*_*SIM 8 javascript css components angular

我有一个具有a countcolor属性的组件.该组件应该显示带有内联样式count<div>s 数,用于将其颜色更改为color.

这是我到目前为止所拥有的:

@Component({
    selector: 'my-control',
    template: `<div *ngFor="let i of dummyArray" style="color: {{color}}"> COLOR = {{color}}</div>`
})
export class MyControl {
    private _count: number;
    @Input() set count(value: string) {
        this._count = +value;
    }
    @Input() set color(value: string) {
        this._color = value;
    }
    get dummyArray(): number[] {
        let ret: number = [];
        for (let i = 0; i < this._count; ++i) ret.push(i);
        return ret;
    }
    get color(): string {
        return this._color;
    }
}
Run Code Online (Sandbox Code Playgroud)

这呈现:

<my-control count="5" color="red">
    <div>COLOR = red</div>
    <div>COLOR = red</div>
    <div>COLOR = red</div>
    <div>COLOR = red</div>
    <div>COLOR = red</div>
</my-control>
Run Code Online (Sandbox Code Playgroud)

现在我有两个问题:

  1. 有没有更好的方法来渲染<div>s count次而不创建虚拟数组?

  2. 更重要的是,内联样式没有设置.如果我硬编码样式style="color: red",它的工作原理.但style="color: {{color}}"事实并非如此.如上所示,元素的渲染没有任何样式.

对于#2,我也尝试过使用这些nativeElement孩子:

@Input() set count(value: string) {
    this._count = +value;
    this.update();
}
@Input() set color(value: string) {
    this._color = value;
    this.update();
}
update(): void {
    for (let i = 0; i < this._count; ++i) {
        this.renderer.setElementStyle(this.elRef.nativeElement.children[i], 'color', this._color);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我得到了访问子元素的异常,因为它们显然不存在.

我该如何解决这些问题?

Gün*_*uer 16

<div *ngFor="let i of dummyArray" style="color: {{color}}>
Run Code Online (Sandbox Code Playgroud)

"之后错过了收盘color}}

应该避免将这种方式绑定到样式,因为它不适用于所有Safari版本(可能还有其他版本).

而是使用

<div *ngFor="let i of dummyArray" [ngStyle]="{'color': color}">
Run Code Online (Sandbox Code Playgroud)

  • 这是有史以来最快的香港专业教育学院得到答案..我计算分钟,以便能够将此标记为正确的答案.. =) (2认同)