[英]How to display a property from my array of objects in Angular /QuizApp
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.
我现在有点困惑,我创建了一个 function 控制台。记录所有问题的所有正确答案,但我不知道如何在我的应用程序中插入它以及如何为每个当前问题做它。
btw.顺便提一句。 sry im newbie, my first post here
对不起,我是新手,我在这里的第一篇文章
This is my component html:这是我的组件 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:这是我的组件 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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.