網站搜尋

angular - 我有兩個按鈕,我需要在 Ionic 中更改其中任一個的顏色


我在我的 HTML 文件中有兩個按鈕

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

所以當使用者點擊200克時,我希望突出其顏色,如果他點擊400,我希望突出400。

我在網上做了很多研究,並找到了像這樣的解決方案 -

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

但這裡發生的情況是,屬性將改為 true,並突出顯示兩個按鈕。

我只想要突顯被按下的按鈕,並保持突顯狀態直到按下另一個按鈕。

答案#1

您可以使用該組件中的屬性來保持所選的值,然後使用 button 的 color 屬性根據當前選定的值來更改它。

請查看這個 可運行的 Stackblitz 演示。

組件:

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

請注意,我使用 [color]="selected === 200 ? 'secondary' : 'primary'" 根據 selected 屬性的值為每個按鈕選擇正確的顏色。