Search code examples
angularangular-directive

Random class for a div inside a ngFor in Angular


I'm doing a web application in Angular 6 and I have an array of string with the name of classes for different colors. I would like to apply them to my div inside a ngFor.

My array of colors:

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];
}

Inside my template:

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

Right now, bgRandom don't appear at all. Only widget-user-header appears correctly.

My goal is to have all the div with a different bgRandom.


Solution

  • Math.random() returns a random float, not an integer, so Math.random() * this.bg.length will not be an integer like an array index.

    You need Math.floor(Math.random() * this.bg.length)

    In addition, you have set bgRandom to a constant value in your initialiser function, so it will be the same for all iteration in your *ngFor.

    You could try creating an array of randomly selected backgrounds, and one for each iteration:

    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>