Angular 中 ngFor 内的 div 的随机 class

Random class for a div inside a ngFor in Angular

我在 Angular 6 中做一个 Web 应用程序,我有一个字符串数组,名称为 类 用于不同的颜色。我想将它们应用到 ngFor.

中的 div

我的颜色数组:

words = [
    'aaa', 'bbb', 'ccc', 'ddd'
  ];

bgRandom = '';

bg = [
   'bg-blue', 'bg-orange', 'bg-red', 'bg-gray', 'bg-maroon',
   'bg-info', 'bg-green', 'bg-fuchsia', 'bg-aqua', 'bg-yellow'
];

ngOnInit() {
   this.bgRandom = this.bg[Math.random() * this.bg.length];
}

在我的模板中:

<ng-container *ngFor="let word of words">
   <div [className]="'widget-user-header' + bgRandom">
      Hi all
   </div>
</ng-container>

目前,bgRandom根本没有出现。只有 widget-user-header 正确显示。

我的目标是让所有 div 具有不同的 bgRandom

Math.random() returns 随机浮点数,不是整数,所以 Math.random() * this.bg.length 不会像数组索引那样是整数。

你需要Math.floor(Math.random() * this.bg.length)

此外,您已在初始化函数中将 bgRandom 设置为常量值,因此在 *ngFor.

中的所有迭代中它都将相同

您可以尝试创建一组随机选择的背景,每次迭代一个:

ngOnInit() {
   this.bgRandom = [];
   for (let i =0; i < this.words.length; i++) {
      bgRandom.push(this.bg[Math.random() * this.bg.length]);
   }
}
<ng-container *ngFor="let word of words; let i = index">
   <div [className]="'widget-user-header' + bgRandom[i]">
      Hi all
   </div>
</ng-container>

其他帖子是正确的。您只设置 bgRandom 一次,因此您只会获得相同的背景颜色。 Math.floor(Math.random() * this.bg.length) 也如@rh16 所说的那样正确。

试试这个:

 getBackgroundColor() {
    return this.bg[Math.floor(Math.random() * this.bg.length)];
  }

在你的 html

[ngClass]="getBackgroundColor()"

可以去掉你的bgRandom 属性.