简体   繁体   English

在 Ionic/Angular 中使用 ngIf 时,如何根据按钮的值更改按钮的颜色

[英]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.我有一个 html 页面,它使用 ngIf 根据我之前在方法调用 getButton() 中提供的数字生成x个按钮,该方法是开始按钮上的单击侦听器。

<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.输出是带有来自colorsArray 的随机值的x个按钮。

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.如何将按钮的颜色更改为按钮的值(代码中的 element.value),即值为 'red' 的按钮必须为 'red',值为 '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.和在 html: 使用ngStyle显示生成的颜色。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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