【发布时间】:2016-09-21 22:47:44
【问题描述】:
我有一个具有count 和color 属性的组件。该组件应该显示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;
}
}
这呈现:
<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>
现在我有两个问题:
有没有更好的方法来渲染
<div>scount次而不创建虚拟数组?更重要的是,没有设置内联样式。如果我硬编码像
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);
}
}
但我在访问子元素时遇到异常,因为它们显然不存在。
我应该如何解决这些问题?
【问题讨论】:
-
如果没有数组,我们
ngFor是没有办法的。您可以创建自定义ngFor指令来执行此操作。使用数字而不是数组来支持ngFor存在问题,但不太可能实现。 -
谢谢你的小费。虽然这很糟糕。在这种情况下,组件的实现很笨拙。
-
您的代码可以稍微优化一下。见stackoverflow.com/questions/36535629/…
-
@GünterZöchbauer .. 喜欢它!.. 这比我现在拥有的要优雅得多.. 感谢您的提示.. =)
标签: javascript css angular components