Home > OS >  How to add multiple buttons using ngfor
How to add multiple buttons using ngfor

Time:11-04

I have the following question:

I have three Buttons that are displayed next to each other in either yellow, red or green. I would like to have them, say, 20 times in a random colour order.

But with my code, I only get them in the order of my statusCases, and only three times. The colour of the buttons is defined by the class they have.

How can I iterate over the list more then once to get more buttons? Do I have to edit my object?

Here is my code:

<button
        *ngFor="let case of statusCases; let i = index"
        class= {{case.cases}}
        >
</button>

(Button in the html)

export class AvgProvisioningTimeComponent implements OnInit {
  @Output() updateTestStatuses = new EventEmitter<string>();
  statusCases: Object[];

  constructor() {
    this.statusCases = [
      {cases: "status__button status__button--red"},
      {cases: "status__button status__button--yellow"},
      {cases: "status__button status__button--green"},
    ];
  }
  
    ngOnInit(): void {
    }
    updateTestStatus(status: string): void {
      this.updateTestStatuses.emit(status);
  }

  
  }

( My class in .ts)

I would be very happy, if anyone could help me :)

CodePudding user response:

HTML:

<div *ngFor="let button of [0, 1, 2, 3, 4, 5]; index as i">
  <button id={{i}}  [ngStyle]="getClassrandom(i)">Hello</button>
</div>

CSS:

.button-colour0 {
  background-color: #2b9696;
}

.button-colour1 {
  background-color: #a611c7;
}

.button-colour2 {
  background-color: #81c016;
}

TS:

  getClassrandom(i: number): any {
    const classesArray = [
      'button-colour0',
      'button-colour1',
      'button-colour2'];
    const element = document.getElementById(i.toString());
    element.className = classesArray[Math.floor(Math.random() * 3)];
  }

I think this is what you want, just change the button-colour with you r css class

CodePudding user response:

first In ES6 using Array fill() method to make 20 items from you array

this.statusCases.fill(20)

then use this function to shuffle the array .

    function shuffle(array) {
  let currentIndex = array.length,  randomIndex;

  // While there remain elements to shuffle.
  while (currentIndex != 0) {

    // Pick a remaining element.
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex--;

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];
  }

  return array;
}

// Used like so

shuffle(this.statusCases);

  • Related