I'm doing a Quiz Simulator App and i want after a button click "Show Answer" to show me the answer of current Question. I'm a bit confused now, I've created a function which console.log all the correct answer from all the questions but i don't know how to Interpolate it in my app and how to do it for every current question.
btw. sry im newbie , my first post here
This is my component 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 appOptionBackground [correctAnswer]="question.correct" class="form-check-label" for="answersRadio">
<input class="form-check-input" type="radio" name="answersRadio" (change)="onAnswer(question.correct)" [disabled]="answerSelected">
{{ question.option }}
</label>
</div>
<button class="btn btn-info btn-block" (click)="showResult()">Show Result</button>
<div *ngIf="result">
Correct Answers: {{correctAnswers}} | Incorrect Answers {{incorrectAnswers}}
</div>
<button (click) ="showAnswer()">show answer</button>
<div>{{correctOption}}
</div>
</div>`
This is my component 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;
correctOption = '';
result = false;
constructor(private questionService: QuestionsService) { }
ngOnInit(): void {
this.questions = this.questionService.getQuestions();
}
onAnswer(option: boolean) {
this.answerSelected = true;
setTimeout(() => {
this.currentQuestion++;
this.answerSelected = false;
}, 2000);
if(option) {
this.correctAnswers++;
} else {
this.incorrectAnswers++;
}
}
showResult() {
this.result = true;
}
showAnswer() {
for (let question of this.questions) {
for (let answer of question.answers) {
if (answer.correct === true ) {
this.correctOption = answer.option;
console.log(this.correctOption);
}
}
}
}
}
Here is an image :
Try this.
showAnswer = () => {
const question = this.questions[this.currentQuestion];
for (let answer of question.answers) {
if (answer.correct === true ) {
this.correctOption = answer.option;
console.log(this.correctOption);
}
}
}