我有两个按钮,我需要在 Ionic 中更改两个按钮中的任何一个的颜色

I have two buttons and I need to change color of either of the two in Ionic

我的 HTML 文件中有两个按钮

<div>
  <button  ion-button outline (click)="selectUnit(200)">200gms</button>
  <button  ion-button outline (click)="selectUnit(400)">400gms</button>
</div>

所以当用户点击 200gms 时,我想突出显示它的颜色,如果他点击 400,我希望它突出显示 400。

我在网上进行了大量研究,找到了解决方案,例如 -

<button [attr.newColor]="addAttribute ? '' : null">Test</button>

但是这里发生的是,该属性将更改为 true,并突出显示两个按钮。

我只想突出显示按下的按钮并保持突出显示,直到按下另一个按钮。

您可以使用该组件的 属性 来保留 selected 值,然后使用 buttoncolor 属性根据当前 selected 值。

请看这个Working stackblitz demo.

分量:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  public selected: number;

  constructor(public navCtrl: NavController) {}

  public selectUnit(unit: number): void {
    this.selected = unit;
  }

}

查看:

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <h2>Welcome to Ionic!</h2>

  <p>Selected: {{ selected }}</p> 

  <div>
    <button [color]="selected === 200 ? 'secondary' : 'primary'" ion-button outline (click)="selectUnit(200)">200gms</button>
    <button [color]="selected === 400 ? 'secondary' : 'primary'" ion-button outline (click)="selectUnit(400)">400gms</button>
  </div>
</ion-content

请注意,我根据 selected 属性.

的值使用 [color]="selected === 200 ? 'secondary' : 'primary'" 到 select 每个按钮的正确颜色