For my school project, I am developing a Quiz App. In the Learning section, I want to implement a feature that changes the color of each answer option when clicked. If the answer is correct, it should turn green; if not, it should turn red. This feature should also be toggleable. I have been struggling for hours with this functionality and feel a bit lost.
Below is the HTML code for my component:
<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">
<ul>
<li (click) = "answerSelected=!answerSelected" [ngClass] = "answerSelected ? 'correct' : 'incorrect'"> {{question.option}}</li>
</ul>
</div>
[…]
This is my TypeScript file for the component:
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";
[…]
In addition, here is the interface for the Question model:
export interface Question {
id: number,
question: string,
answers: {option: string, correct:boolean}[],
description: string
}
If you need a visual reference, check out this image link.