如何在Ionic2中单击时更改按钮颜色?

时间:2017-05-25 23:49:33

标签: angular typescript ionic2

我正在bluestacks的android模拟器上进行测试,无论离子按钮的自然响应能力似乎都不起作用。我想确保此按钮颜色在点击时发生变化。 我是用css做什么的?离子对此并不清楚。

这是我的按钮

<button ion-button block (click)="addEvent();">Add Event</button>

4 个答案:

答案 0 :(得分:11)

在component.ts文件中:

声明一个变量:

use

将您的HTML编辑为: -

buttonColor: string = '#000'; //Default Color

在您的函数中执行以下更改: -

<button ion-button block (click)="addEvent();" [ngStyle]="{'background-color': buttonColor}">Add Event</button>

答案 1 :(得分:2)

更多 ionic 方法,就是使用颜色属性,如下所示:

80d82ee

在你看来:

@Component({...})
export class HomePage {

    public ionicNamedColor: string = 'primary';

    constructor() {}

    public toggleNamedColor(): void {
      if(this.ionicNamedColor === 'primary') { 
        this.ionicNamedColor = 'secondary'
      } else {
        this.ionicNamedColor = 'primary'
      }
    }

}

请注意,颜色应添加到<button (click)="toggleNamedColor()" ion-button [color]="ionicNamedColor">Click me!</button>

的指定颜色变量中
variables.scss

如果您不想使用指定的颜色变量,那么您只需更改按钮的背景颜色,如下所示:

$colors: (
  primary:    #488aff,
  secondary:  #32db64,
  danger:     #f53d3d,
  light:      #f4f4f4,
  dark:       #222
);

在你看来:

@Component({...})
export class HomePage {

  public hexColor: string = '#000000';

    constructor() {}

    public toggleBackgroundColor(): void {
      if(this.hexColor === '#000000') { 
        this.hexColor = '#dddddd'
      } else {
        this.hexColor = '#000000'
      }
    }

}

请在 this plunker中查看两种方法。

答案 2 :(得分:1)

在我的HTML中,我有这个:

<ion-item class="text" *ngFor="let item of question.data.answers; let i = index;">
<button (click)="itemClicked(item, item, i, question.key, question.data)" [class.incorrect]="!item.correct && whatISelected == i" [ngStyle]="item.correct ? {'background-color': buttonColor } : null " > {{ item.answer }}</button>

在我的组件中:

// Declared before constructor component
selectedItem: string
whatISelected: string
buttonColor: string

itemClicked(item, answer, iSelect, key, question) {
   // keep selectedItem for each item
   this.hasAnswered = true;
   if ( answer.correct ) {
     this.selectedItem = answer.correct;
     this.buttonColor = '#32db64'
   } else {

     this.whatISelected = iSelect
     this.buttonColor = '#32db64'
   }
}

答案 3 :(得分:0)

<button *ngIf="this._var == true" (click)="this.itemClicked();" class="button1" >My Button 1</button>  

<button *ngIf="this._var == false" (click)="this.itemClicked();" class="button2" >My Button 2</button>


    public itemClicked(){

    if(this._var != false){
     this._var == false;
    }else{
     this._var == true;
    }

    }