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

Asked

Viewed 45 times

1

I’m testing a method here, to add tags, I want one of each color, however, with ngFor Angular, the colors are all the same to each new tag added. Follows 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()
}

1 answer

0


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

{ 
   select : string,
   color : string
}

It would only change his method addItem for something like this:

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

So yours ngFor would look more or less 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>
  • Great, it worked out! Thanks Lucas!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.