【问题标题】:How can I change the color of my button based on its value when using ngIf in Ionic/Angular在 Ionic/Angular 中使用 ngIf 时,如何根据按钮的值更改按钮的颜色
【发布时间】:2020-11-09 15:20:19
【问题描述】:

我有一个 html 页面,它使用 ngIf 根据我之前在方法调用 getButton() 中提供的数字生成 x 个按钮,getButton() 是开始按钮上的点击监听器。

<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>

按钮的值从颜色数组中随机化,然后推入长度等于所需按钮数量的按钮值数组中。

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

输出是 x 个带有来自 colorsArray 的随机值的按钮。

如何将按钮的颜色更改为按钮的值(代码中的element.value),即值为'red'的按钮必须着色为'red',值为'red'的按钮“蓝色”必须是蓝色的。

【问题讨论】:

  • 使用 ngclass 或 ngstyle
  • 尝试在 ngFor 之后添加 [style.color]="element.value"。

标签: javascript html angular ionic-framework


【解决方案1】:

你可以通过这个函数生成随机颜色:

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;    
}

并用颜色初始化你的数组:

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

在 html 中: 使用ngStyle 显示生成的颜色。

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

【讨论】:

    猜你喜欢
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-02
    • 2019-10-13
    • 2012-07-05
    • 1970-01-01
    相关资源
    最近更新 更多