简体   繁体   中英

Why do elements already created inherit the style of the new element, on ngFor in Angular?

I am trying add a new tags, but I want that they change their background-colors .. how can I do that?

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

select: string
items = []
randomcolor: any

addItem(item){
  this.items.push(item)
  console.log(this.getRandomColor())
}


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()
}

They are staying with the same background-colors.

HTML :

<input type="text" class="form-control" [(ngModel)]="select">
<button type="button" (click)="addItem(select)">Enviar</button>
<div *ngFor="let i of items">
  <div class="badge badge-pill" [style.background]="color[i]">
    {{ i }}
  </div>
</div>

TS :

select: string
items = []
color: any = {};

addItem(item) {
  this.items.push(item);
  this.color[item] = this.randomColor;
}

get randomColor() { return '#' + ('' + Math.random().toString(16).split('.')[1]).slice(-6); }

The problem is that you have single randomcolor attribute which is shared among all of your items. Therefore, the background color may change but they all will have the same background color.

Try this

select: string
items = []

addItem(item){
  const color = this.getRandomColor();
  this.items.push({value: item, bgColor: color});
}


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

In html,

<input type="text" class="form-control" [(ngModel)]="select">
 <button type="button" (click)="addItem(select)">Enviar</button>
 <div *ngFor="let item of items">
   <div class="badge badge-pill" [ngStyle]="{'background-color' : item.bgColor}">{{ item.value }}
   </div>
 </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM