How to change buttons color on click of button in ionic 4

梦想与她 提交于 2021-01-29 17:27:53

问题


I want to change buttons color on click of button.

I am creating a quiz application.

On click of a button if the answer is correct the color should be changed to green and if wrong it should be changed to red.

This is worked. I have done this.

But now the issue is if the answer is wrong then its color changed to red and correct answers button color changed to green.

How to do this?

play-quiz.html

<ion-list>
    <ion-row class="marginTop">
      <ion-col class="border ion-text-center">
        Grand Central Terminal, Park Avenue, New York is the world's
      </ion-col>
    </ion-row>

    <ion-row class="marginTop">
      <ion-col class="ion-text-center">
        <ion-button id="1" #first class="btn" expand="block" (click)="onClick(first,'1')">
          Largest Railway Station
        </ion-button>
      </ion-col>
    </ion-row>

    <ion-row>
      <ion-col class="ion-text-center">
        <ion-button id="2" #second class="btn" expand="block" (click)="onClick(second,'2')">
          highest railway station
        </ion-button>
      </ion-col>
    </ion-row>

    <ion-row>
      <ion-col class="ion-text-center">
        <ion-button id="3" #third class="btn" expand="block" (click)="onClick(third,'3')">
          longest railway station
        </ion-button>
      </ion-col>
    </ion-row>

    <ion-row>
      <ion-col class="ion-text-center">
        <ion-button id="4" #four class="btn" expand="block" (click)="onClick(four,'4')">
          None of the above
        </ion-button>
      </ion-col>
    </ion-row>

    <ion-row>
      <ion-col>
        <ion-button class="btn right" expand="small">
          Next
        </ion-button>
      </ion-col>
    </ion-row>

  </ion-list>

play-quiz.ts.

answer: any = "1";

onClick(ionicButton, btn: any) {
      if(this.answer == btn){
        ionicButton.color =  'success';
      } else {
        ionicButton.color =  'danger';
      }
  }


回答1:


In HTML:

<ion-button [ngClass]="isClicked() ? 'btn red': 'btn'" (click)="onClick()">Toggle</ion-button>

In TS:

isClick: boolean=false;

isClicked(){
 return this.isClick;
}

onClick(){
 this.isClick=!this.isClick;
}

The functionality you can modify in onClick() method. Based on the value isClicked() returned it will append the class 'red' (if it returns true, it will add, else no).

CSS you can all the required styles.

Hope this helps.



来源:https://stackoverflow.com/questions/60929233/how-to-change-buttons-color-on-click-of-button-in-ionic-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!