Angular中ngFor内的div的随机类

问题描述 投票:1回答:2

我在Angular 6中做了一个Web应用程序,我有一个字符串数组,其中包含不同颜色的类名。我想将它们应用到我在div内的ngFor

我的颜色数组:

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

angular angular-directive
2个回答
3
投票

Math.random()返回一个随机浮点数,而不是一个整数,所以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>

0
投票

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

试试这个:

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

并在你的HTML中

[ngClass]="getBackgroundColor()"

你可以摆脱你的bgRandom财产。

© www.soinside.com 2019 - 2024. All rights reserved.