Ionic5中如何使用多条件ng-class实现答题按钮样式动态切换
代码修改方案
1. 调整quiz.ts逻辑
首先在类中新增2个全局状态变量:
isAnswered = false; // 标记当前题目是否已完成作答 currentCorrectAnswer: string = ''; // 存储当前题目的正确答案
替换原有choice函数为以下版本:
choice(ans, qn) { // 已作答的题不再响应点击 if(this.isAnswered) return; this.selectedItem = ans.choice; // 格式化当前题目正确答案存储 this.currentCorrectAnswer = qn.corect.toString().replace(/\s/g, ""); // 标记为已作答 this.isAnswered = true; if (this.selectedItem.toString().replace(/\s/g, "") == this.currentCorrectAnswer) { console.log('correct'); this.incrimentScore(); this.textToSpeech.speak({ text: 'correct Answer.', locale: 'en-US', rate: 0.7 }) .then(() => console.log('Done') ) .catch((reason: any) => console.log(reason) ); } else { this.textToSpeech.speak({ text: 'you are wrong', locale: 'en-US', rate: 0.7 }) .then(() => console.log('Done') ) .catch((reason: any) => console.log(reason) ); } } // 新增切换题目时的状态重置方法,滑动到下一题时调用即可 resetQuestionState() { this.isAnswered = false; this.selectedItem = ''; this.currentCorrectAnswer = ''; }
2. 修改quiz.html模板的样式绑定逻辑
替换答案选项的ion-card节点代码:
<ion-card (click)="choice(ans,qn, indexOfelement)" *ngFor="let ans of qn.Answer; let indexOfelement=index;" [ngClass]="{ 'correct': isAnswered && ans.choice.toString().replace(/\s/g, '') == currentCorrectAnswer, 'wrong': isAnswered && ans.choice == selectedItem && ans.choice.toString().replace(/\s/g, '') != currentCorrectAnswer }" > <ion-card-content> {{ans.choice}} </ion-card-content> </ion-card>
3. 添加对应样式
在页面的scss/css文件中新增样式:
.correct { background-color: #2ecc71 !important; color: #fff !important; } .wrong { background-color: #e74c3c !important; color: #fff !important; }
内容的提问来源于stack exchange,提问作者Jimmy Boaz
相关产品推荐
相关产品推荐

