javascript - 如何根据角度的正确或错误答案动态添加ngclass?
问题描述
export class QuestionsPage implements OnInit {
question = [];
isAnswerd: boolean = false;
wrong: boolean = false;
qIndex: number = 0;
indicatorlength = [];
score: number = 0;
min: number = 0;
sec: any = 0;
constructor(private service: AppServiceService) {}
ngOnInit() {
this.question = this.service.question;
this.renderIndicator();
this.timeCount();
}
checkQuestion(ans) {
console.log(ans.target.id);
document.getElementById(ans.target.id).style.color = "white";
document.getElementById(ans.target.id).style.backgroundColor = "red";
const correctOption = this.question[this.qIndex].answer;
if (ans == correctOption) {
this.score++;
this.isAnswerd = true;
this.renderIndicator("correct", this.qIndex);
} else {
this.isAnswerd = true;
}
}
nextQuestion() {
document.getElementById("A").style.color = "black";
document.getElementById("A").style.backgroundColor = "#cccccc";
document.getElementById("B").style.color = "black";
document.getElementById("B").style.backgroundColor = "#cccccc";
document.getElementById("C").style.color = "black";
document.getElementById("C").style.backgroundColor = "#cccccc";
document.getElementById("D").style.color = "black";
document.getElementById("D").style.backgroundColor = "#cccccc";
this.isAnswerd = false;
if (this.qIndex < this.question.length - 1) {
this.qIndex++;
} else {
}
}
renderIndicator(ansType?: string, qIndex?: number) {
const totalQuestions = this.question.length;
for (let i = 0; i < totalQuestions; i++) {
if (i < 9) {
const a = i + 1;
const num = "0" + a;
this.indicatorlength.push(num);
} else {
this.indicatorlength.push(i + 1);
}
if (ansType == "correct") {
} else {
}
}
}
}
我想在答案正确时改变颜色,使用 bg-primary 类,否则使用 bg-danger。用户单击答案时如何管理背景颜色?Angular 中的 NgClass 指令将类名动态分配给特定的索引值。我想在答案正确时改变颜色,使用 bg-primary 类,否则使用 bg-danger。用户单击答案时如何管理背景颜色?Angular 中的 NgClass 指令将类名动态分配给特定的索引值
解决方案
使用类似 -> lib的东西,动态部分会更容易和更简单Render2
之后,您可以轻松地在所选事件中动态添加your special class
import { Renderer2 } from '@angular/core';
constructor(private render:Renderer2) { }
像这样处理您的
selected event
或回答点击
HandleCorrectAnswer(event:any) {
//this.renderer.addClass(event.target,"some selected answer NgClass here");
this.renderer.addClass(event.target,"bg-primary");
//... do something more
}
在 html 中:
<button class="yourDefaultClasses" (click)="HandleCorrectAnswer()">User Selected Answer</button>
推荐阅读
- smtp - BizTalk SMTP 消息“msg_Email”的“PartAttachment”部分在构造块的末尾包含空值
- mysql - 如何使用特定规则将 TOP 3 值选择到 3 列?
- json - JSON 模式不验证缺少的属性
- java - 为什么 Eclipse 中的 Codota 插件不起作用?
- c - fopen 读取无效的参数 C
- php - 使用邮递员的文件导出 HTTP POST 请求不起作用
- c - 如何在另一个数组中声明一个数组而不定义大小
- c# - Ozeki VoIP SDK 捕捉电话的新闻事件
- python - Twitter、tweepy、search_30_day - 与正常外观相比不会产生任何结果
- javascript - 过滤具有反向关系的对象时超出最大调用堆栈大小(领域 10.1.1)