更改onclick

时间:2019-05-29 07:31:29

标签: angular ionic-framework ionic4

我有两个按钮,分别为 YES NO ,它们的颜色(即背景色)是浅色的,

enter image description here

  

当用户单击

  • 按钮背景颜色应更改为绿色(即成功),并且应为浅色,如下所示:

enter image description here

  

当用户单击

  • 按钮的背景色应更改为红色(有危险),并且应为浅色,如下所示:

enter image description here

DEMO

在冲浪时我看到了这个 question 。在这里,他们只需按点击即可更改一种按钮颜色。但根据我的要求,按钮的颜色都应在点击时更改。

代码

HTML

<ion-content padding>
  <ion-item lines="none">
  <ion-button class="btn-1" expand="full" color="light" >Yes</ion-button>
   <ion-button class="btn-2" expand="full"  color="light" >No</ion-button> 
  </ion-item>
</ion-content>

CSS

.btn-1{
width:45%;
float:left;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}
.btn-2{
width:45%;
float:right;
padding:0px 5px 0px 5px;
margin-bottom:20px;
}

TS

 import { Component } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.css'],
})
export class HomePage {

}

4 个答案:

答案 0 :(得分:1)

3个值表示您不能使用布尔值。但是您可以使用数字:

buttonValue = 0;
<ion-button class="btn-1" expand="full" [color]="buttonValue > 0 ? 'success' : 'light'" (click)="buttonValue = 1">Yes</ion-button>
<ion-button class="btn-2" expand="full" [color]="buttonValue < 0 ? 'danger' : 'light'" (click)="buttonValue = -1">No</ion-button> 

答案 1 :(得分:1)

您可以在此处尝试此代码或点击此链接stackblitz

编辑模板 home.page.html

<ion-button (click)="activeNow('green')" class="btn-1" expand="full" [color]="(selectItem==='green')? 'success':'light'" >Yes</ion-button>
<ion-button (click)="activeNow('red')" class="btn-2" expand="full"  [color]="(selectItem==='red')? 'danger':'light'"  >No</ion-button> 

并更新 home.page.ts

selectItem:string='';
activeNow(item:string) {
  this.selectItem=item;
}

答案 2 :(得分:0)

尝试这样:

TS:

isYesClicked:boolean = false
isNoClicked:boolean = false

HTML:

<ion-button class="btn-1" expand="full" (click)="isYesClicked=true;isNoClicked=false" [color]="isYesClicked?'success':'light'"  >Yes</ion-button>


<ion-button class="btn-2" expand="full"  color="light" (click)="isYesClicked=false;isNoClicked=true" [color]="isNoClicked?'danger':'light'">No</ion-button> 

答案 3 :(得分:0)

您可以像这样用ngClass点击添加课程

<ion-content padding>
  <ion-item lines="none">
    <ion-button
      [ngClass]="yesButtonTriggered ? 'greenButton': 'light'"
      (click)="yesButton()"
      class="btn-1"
      expand="full"
      color="light"
    >Yes</ion-button>
    <ion-button
      [ngClass]="noButtonTriggered ? 'redButton': 'light'"
      (click)="noButton()"
      class="btn-2"
      expand="full"
      color="light"
    >No</ion-button>
  </ion-item>
</ion-content>

在您的TS中

  yesButtonTriggered = false;
  noButtonTriggered = false;

  yesButton() {
    // do your stuff
    this.yesButtonTriggered = true;
    this.noButtonTriggered = false;
  }

  noButton() {
    // do your stuff
    this.noButtonTriggered = true;
    this.yesButtonTriggered = false;
  }