点击功能上每个元素的角度类绑定

Posted

技术标签:

【中文标题】点击功能上每个元素的角度类绑定【英文标题】:Angular classBinding for every single element on click function 【发布时间】:2022-01-08 01:36:16 【问题描述】:

我正在为一个学校项目做一个测验应用程序。在学习部分,当我点击每个可能的答案时,我希望它具有功能,如果它是错误答案,它应该将颜色变为红色,当它正确答案时变为绿色。它应该太亮了。我挣扎了这么多小时,我瘦了,我有点迷路了。

这是我的组件 html

    <div class="container p-5 ">
      <div class="row">
        <div class = "col-sm-8 offset-2">
          <p class = "text-center">currentQuestion + 1  of questions.length </p>
          <h3>questions[currentQuestion].question</h3>
          <div  *ngFor="let question of questions[currentQuestion].answers">
            <!-- <label   class="form-check-label" for="answersRadio">
                <input (change) = "toggleCheck($event)" class="form-check-input" type="checkbox" name="answerSelected" ([ngModel])="question.correct" >
               question.option  question.correct
              <span id="text" style="display: none;">answerCheckText </span>
            </label> -->
            <ul>
              <li (click) = "answerSelected=!answerSelected" [ngClass] = "answerSelected ? 'correct' : 'incorrect'"> question.option</li>
            </ul>
          </div>
          <!-- <button class="btn btn-info btn-block" (click)="showResult()">Show Result</button>
          <div *ngIf="result">
            Correct Answers: correctAnswers |  Incorrect Answers incorrectAnswers
          </div> -->
          <button [ngClass]="buttonText" class="btn btn-info btn-block"  (click)="showAnswer(); toggleShow()">buttonText</button>
            <div *ngIf="show">
            <div >correctOption </div>
            <span>description</span>
          </div>
          <button class="btn btn-danger btn-block" (click)="previousQuestion()">Previous</button>
          <button class="btn btn-success btn-block" (click)="nextQuestion()">Next</button>
        </div>
    </div>
    
    </div>

这是我的组件 ts 文件:


    import  Component, OnInit  from '@angular/core';
    import  QuestionsService  from '../shared/questions.service';
    import Question from '../shared/question';
    
    @Component(
      selector: 'app-question-learn',
      templateUrl: './question-learn.component.html',
      styleUrls: ['./question-learn.component.css']
    )
    export class QuestionLearnComponent implements OnInit 
    questions: Question[] = [];
    
    currentQuestion = 0;
    answerSelected = false;
    correctAnswers = 0;
    incorrectAnswers = 0;
    
    buttonText = "Show Hint";
    
    show = false;
    
    correctOption = '';
    
    description = '';
    
    answerCheckText = '';
    
    result = false;
    
    constructor(private questionService: QuestionsService)  
    
      ngOnInit(): void 
        this.questions = this.questionService.getQuestions();
    
      
    
    // toggleCheck(event: any) 
    //   let check = event.target.checked;
    //   if (check) 
    //     let question = this.questions[this.currentQuestion];
    //     for (let answer of question.answers) 
    //         if (answer.correct === true ) 
    //           console.log("correct");
    //          else 
    //           console.log("incorrect");
    //        
    //        break;
    //     
    //   
    
    
      // onAnswer () 
      //   this.answerSelected = true;
    
      // 
    
      check(status: any) 
        if(status.correct)
          return 'correct';
         else
          return  'incorrect;'
        
      
    
      showResult() 
        this.result = true;
      
    
      toggleShow() 
    
        this.show = !this.show;
    
        if(this.show === false) 
          this.buttonText = 'Show Answer';
         else 
          this.buttonText = 'Hide Answer';
        
      
    
      showAnswer() 
        let question = this.questions[this.currentQuestion];
        for (let answer of question.answers) 
          if (answer.correct === true ) 
            this.correctOption = answer.option;
            this.description = question.description;
          
        
      
    
      nextQuestion() 
        if(this.currentQuestion >= this.questions.length - 1 ) 
          console.log("exceeded the maximum number");
         else 
          this.currentQuestion++;
          this.show = false;
          if(this.show === false) 
            this.buttonText = 'Show Answer';
           else 
            this.buttonText = 'Hide Answer';
          
    
        
      
    
      previousQuestion() 
        if(this.currentQuestion <= 0 ) 
          console.log("exceeded the maximum number");
         else 
          this.currentQuestion--;
          this.show = false;
          if(this.show === false) 
            this.buttonText = 'Show Answer';
           else 
            this.buttonText = 'Hide Answer';
          
        
      
    
    

这是我的问题界面:

export interface Question 
  id: number,
  question: string,
  answers: option: string, correct:boolean[],
  description: string


这是一个更好的可视化图像: image

【问题讨论】:

能否分享一下'正确'和'不正确'的css类的代码? 你可以在下面看到它们,在我的第二篇文章中 :) 查看我创建的这个基本示例并根据您的需要进行调整。 stackblitz.com/edit/… 基本上你只需在点击时添加类。只要正确选择了答案,selectedIndex 是可选的,其余部分显示红色背景。 谢谢我已经实现了这个功能,它对我有帮助,但它只适用于单选题,而不是当有多个正确答案时,我得到一个小错误,“类型‘数字’是不能分配给类型'null'。”因此,我将“ selectedIndex= null; ”设置为任何类型----> selectedindex:any = null 并且现在可以使用。你能帮我解决多个问题吗? 【参考方案1】:

所以我仍然在挣扎,但我认为我已经向前迈出了一步。 类是绑定的,但我不知道如何使此功能正常工作,单击时我只得到绿色的所有答案。我想问题在于将这些 question.correct 属性绑定到我的函数,以便它正常工作。

我添加了新变量:

colorClass = 'normal';

有我的功能:

onAnswer() 
    let question = this.questions[this.currentQuestion];
    for (let answer of question.answers) 
        if (answer.correct === true  ) 
          this.colorClass = 'correct';
         else 
          this.colorClass = 'incorrect';
       
    

html:

  <h3>questions[currentQuestion].question</h3>
      <div  *ngFor="let question of questions[currentQuestion].answers">
        <ul>
          <li [className] ="colorClass"   (click) = "onAnswer()">question.option</li>
        </ul>
      </div>

我的 CSS 类

ul 
  display: flex;
  width: 80%;
  margin: 0;
  padding: 0;
  flex-flow: column;


ul li.normal 
  list-style: none;
  line-height: 2;
  border: 1px solid #cdd2d2;
  margin-bottom: 10px;
  border-radius: 15px;
  text-align: center;
  cursor: pointer;


li.normal:hover 
  background-color: whitesmoke;


li.correct 
  list-style: none;
  line-height: 2;
  border: 1px solid #cdd2d2;
  margin-bottom: 10px;
  border-radius: 15px;
  text-align: center;
  cursor: pointer;
  border: 1px solid green;
  background-color: green;
  color: white;
  font-weight: 600;


li.incorrect 
  list-style: none;
  line-height: 2;
  border: 1px solid #cdd2d2;
  margin-bottom: 10px;
  border-radius: 15px;
  text-align: center;
  cursor: pointer;
  border: 1px solid red;
  background-color: red;
  color: white;
  font-weight: 600;


【讨论】:

尝试 [className]="question.correct ? '正确' : '不正确'"

以上是关于点击功能上每个元素的角度类绑定的主要内容,如果未能解决你的问题,请参考以下文章

将数据从父范围绑定到角度树控件中节点中的元素的方法?

如何使用角度链接功能禁用除特定元素之外的所有点击

无法将范围变量绑定到角度js中的html元素

取消绑定 ng-click 以获取角度中的动态 dom 元素

从技术角度来看,Selenium 如何点击网页上的元素?

跨度元素上的动态 CSS 类 - 角度 4