首页 > 解决方案 > 如何根据角度的正确或错误答案动态添加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 指令将类名动态分配给特定的索引值

在此处输入图像描述

标签: javascriptangularionic-framework

解决方案


使用类似 -> lib的东西,动态部分会更容易和更简单Render2

之后,您可以轻松地在所选事件中动态添加your special class

  1. import { Renderer2 } from '@angular/core';

  2. constructor(private render:Renderer2) { }

  3. 像这样处理您的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>

推荐阅读