代码之家  ›  专栏  ›  技术社区  ›  neeraj Saxena

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

  •  2
  • neeraj Saxena  · 技术社区  · 7 年前

    我的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,并高亮显示两个按钮。

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

    1 回复  |  直到 7 年前
        1
  •  1
  •   sebaferreras    7 年前

    可以使用该组件中的特性来保留选定值,然后使用 color 属性 button 根据当前选定的值进行更改。

    请看看这个 Working stackblitz demo

    enter image description here

    组成部分 :

    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 所有物