Angular2 组件 - 动态内联样式

Angular2 Components - Dynamic Inline Styles

我有一个组件有一个 count 和一个 color 属性。该组件应该显示 count<div> 的行内样式,用于将其颜色更改为 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;
    }
}

这呈现:

<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>

现在我有两个问题:

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

  2. 更重要的是,没有设置内联样式。如果我硬编码像 style="color: red" 这样的样式,它就可以工作。但是 style="color: {{color}}" 没有。正如您在上面看到的那样,该元素呈现时没有任何样式。

对于#2,我也尝试过使用nativeElement的children:

@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);
    }
}

但是我在访问 child 元素时遇到异常,因为它们显然不存在。

我该如何解决这些问题?

<div *ngFor="let i of dummyArray" style="color: {{color}}>

color}}

之后缺少结尾 "

应避免以这种方式绑定样式,因为它不适用于所有 Safari 版本(也许还有其他版本)。

改为使用

<div *ngFor="let i of dummyArray" [ngStyle]="{'color': color}">

关于你的第一个问题:

要创建包含十个 undefined 个元素的数组,您可以这样做:

@Component({
  selector: 'my-app',
  template: `<div *ngFor="let i of arr(10); let index=index">hello {{index}}</div>`
})
export class AppComponent {
  arr=Array;
}

check this plunk