【发布时间】:2017-10-23 03:12:16
【问题描述】:
我目前正在使用 Angular 2/4 开发一个网站。谁能告诉我如何使用 Angular 将类动态添加到 Div 元素。显然,我正在尝试向通过 *ngFor 显示的每个 div 背景添加随机引导 css 颜色类
//Component class
bgarray = ["bg-primary","bg-success","bg-danger","bg-warning","bg-warninig"];
getColour()
{
this.bgColour = this.bgarray[Math.floor(Math.random()*this.bgarray.length)];
return this.bgColour;
}
我尝试使用 [ngClass] 调用一个函数,该函数返回一个单独的类,如“bg-danger”或“bg-warning”等。
<div class="bg-gray-lighter progress progress-xs">
<div class="progress-bar progress-xs " [style.width]="device.value" [ngClass]="getColour()" ></div>
</div>
但随后会抛出错误"expressionChangedAfterItHasBeenCheckedError"
您能否告诉我是否有任何解决方法可以为不同的进度条动态添加不同的背景颜色?
非常感谢。如果您能提供帮助,将不胜感激
这是我想要实现的目标的预览。
PS:进度条数量可能会有所不同,下图包含 4 个,但将来可能会达到 16 个或更多,因此我想为它们动态分配随机颜色。
【问题讨论】:
-
不要绑定到方法,而是将值分配给字段并绑定到该字段。