how to use ng-class with multiple condition in ionic 5

2k Views Asked by At

i created quiz app with ionic and angular, i want to implement when user choose correct answer the button should change to green, and when choose the wrong answer the button should change to red and show the correct answer with green color. bellow is my code quiz.html

<ion-slide *ngFor="let qn of Questions">
  <ion-grid>
    <ion-row>
      <ion-col size-xs="12">
        <ion-card style="min-height:100px" class="qn_card">
          <ion-card-header>
            <ion-text style="float:left; font-weight:600">{{slideCount}} of {{Questions.length}}</ion-text>
            <ion-text>{{score}}</ion-text>
            <ion-text style="float:right; font-weight:00">{{display }}</ion-text>
          </ion-card-header>
          <ion-card-content style="float:left;">
            <p>{{qn.question}}</p>
          </ion-card-content>
        </ion-card>
        <div class="qn" style="margin-top:25%">
          <ion-card (click)="choice(ans,qn, indexOfelement)"
            *ngFor="let ans of qn.Answer; let indexOfelement=index;"
            [ngClass]="{'activated':ans.choice==selectedItem}">
            <ion-card-content>
              {{ans.choice}}
            </ion-card-content>
          </ion-card>
        </div>
      </ion-col>
    </ion-row>
  </ion-grid>
</ion-slide>

this is quiz.ts

choice(ans,qn)  { 
this.selectedItem = ans.choice
if (this.selectedItem.toString().replace(/\s/g, "") == qn.corect.toString().replace(/\s/g, "")) {
  console.log('corect');
  this.incrimentScore()
  this.textToSpeech.speak({
    text: 'corect Answer.',
    locale: 'en-US',
    rate: 0.7
  })
    .then(() =>
      console.log('Done')
    )
    .catch((reason: any) =>
      console.log(reason)
    );
} else {
  // console.log('wrong')
  this.textToSpeech.speak({
    text: 'your wrong',
    // +qn.corect
    locale: 'en-US',
    rate: 0.7
  })
    .then(() =>
      console.log('Done')
    )
    .catch((reason: any) =>
      console.log(reason)
    );
}   

}

1

There are 1 best solutions below

0
On
[ngClass]="{'className':  condition,'className':  condition, 'className': condition}"

Other option

[ngClass]="Condition ? 'className' : Condition ? 'className' : Condition ? 'className' : 'defaultclassName'"