Does anyone know why the elements already added inherit the new colors?

1

I'm testing a method here, for adding tags, I want one of each color, but with the Angle ngFor, the colors are all the same with each new tag added. Here is the code:

<div class="container">
 <input type="text" class="form-control" [(ngModel)]="select">
 <button type="button" (click)="addItem(select)
           (click)="setColor()">Enviar</button>
  <div *ngFor="let i of items" class="badge badge-pill">
    <div class="badge badge-pill" [ngStyle]="{'background-color' : 
                                                   randomcolor}">{{ i }}
  </div>
 </div>
</div>
select: string
items = []
randomcolor: any

addItem(item){
  this.items.push(item)
}

getRandomColor(){
 var letters = '0123456789ABCDEF'.split('');
 var color = '#';
   for (var i = 0; i < 6; i++){
     color += letters[Math.floor(Math.random() * 16)];
   }
 return color;
}


setColor(){
   this.randomcolor = this.getRandomColor()
}
    
asked by anonymous 12.03.2018 / 21:50

1 answer

0

The reason for this is because randomcolor is global, and every time you change it, you change it for everyone, it might be better to organize the items in that format:

{ 
   select : string,
   color : string
}

Just change your addItem method to something like this:

addItem(item){
    this.items.push({ select : item, color : this.getRandomColor() });
}

So your ngFor would look something like this:

<div *ngFor="let i of items" class="badge badge-pill">
    <div class="badge badge-pill" [ngStyle]="{'background-color' : i.color}">
        {{ i.select }}
    </div>
</div>
    
13.03.2018 / 14:09