Unnati Patadia
Unnati Patadia

Reputation: 732

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

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

enter image description here

Upvotes: 0

Views: 8256

Answers (2)

You can achieve this from below CSS code:

ion-button:focus {
        --background: #067856;
        --color: white;
      }

Upvotes: 0

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.

Upvotes: 2

Related Questions