简体   繁体   中英

How can I change the color of my button based on its value when using ngIf in Ionic/Angular

I have a html page that generates x number of buttons using ngIf based on a number I feed it earlier in a method call getButton() which is a click listener on the start button.

<ion-content>

  <ion-button (click)="getButton(15)"> 
    Start
  </ion-button>

  <ion-button *ngFor ="let element of buttonArray" (click)="checkAnswer(element.value)"> 
    {{ element.value }}
  </ion-button>

</ion-content>

The value of the button is randomized from an array of colors and then pushed into an array of button values whose length is equal to the number of buttons required.

colorsArray : string[] = ['Red', 'Blue', 'Green', 'Yellow']

getButton(i: number){
    let c: number ;
    for (c=0; c<i; c++) {
      this.buttonArray.push((this.colorsArray[(Math.floor(Math.random()*4))])
    }
   }

The output is x number of buttons with random values from the colorsArray.

How do I change the color of the button to the value of the button (element.value in the code), that is, a button with the value 'red' must be colored 'red' and a button with the value 'blue' must be colored blue.

You Can Generate Random Colors by This Function:

getRandomColor(){
    let color = "#";
    for (let i = 0; i < 3; i++)
    {
        let part = Math.round(Math.random() * 255).toString(16);
        color += (part.length > 1) ? part : "0" + part;
    }
   return color;    
}

and initialize your array with colors:

this.buttonArray.forEach((e)=>{
   e.color = this.getRandomColor();
})

and In html: use ngStyle to show generated color.

<ion-button *ngFor ="let element of buttonArray" (click)="checkAnswer(element.value)" [ngStyle]="{background-color: element.color}"> 
    {{ element.value }}
</ion-button>

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