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



我正在bluestacks android模拟器上测试这个,任何自然响应能力离子按钮似乎都不起作用。我想确保以后此按钮颜色在单击时会发生变化。我用 css 做还是什么?Ionic对此并不清楚。

这是我的按钮

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

在 component.ts 文件中:

声明一个变量:

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

将您的 HTML 编辑为:-

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

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

addEvent(){
this.buttonColor = '#345465'; //desired Color
/*
YOUR FUNCTION CODE
*/
}

一种更离子的方法是像这样使用颜色属性

@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'
      }
    }
}

在您看来:

<button (click)="toggleBackgroundColor()" ion-button [style.background-color]="hexColor">Click me!</button>

请看一下在这个 plunker 中的两种方法。

在我的 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'
   }
}
<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;
    }
    }

相关内容

  • 没有找到相关文章

最新更新