[英]Why is my Angular component method not working?
I'm making a basic quiz application. 我正在做一个基本的测验应用程序。 Whenever the user answers the question I want the answer to be determined as correct/incorrect, move to the next question, and hide the correct / incorrect messages.
每当用户回答问题时,我希望将答案确定为正确/不正确,就移至下一个问题,并隐藏正确/不正确的消息。
Problem: The h2 correct/incorrect messages are not hiding themselves when this.correct / this.incorrect is set to null/false. 问题:当this.correct / this.incorrect设置为null / false时,h2正确/不正确的消息不会隐藏自己。
I want these h2s to display for 2 sections before going on to the next question. 在继续下一个问题之前,我希望这些h2显示2个部分。
Here is the part of the html template that should be toggling, but they're not.: 这是html模板的一部分,应该切换,但不是。
<h2 *ngIf="correct">Correct</h2>
<h2 *ngIf="incorrect">Incorrect! The answer is {{ questions[counter].answer }}</h2>
Here is one component method: 这是一种组件方法:
compareAnswer(userAnswer) {
const currentAnswer = this.questions[this.counter].answer;
if (currentAnswer.includes(userAnswer.answer)) {
console.log('Correct!');
this.correctAnswers += 1;
this.correct = true;
} else {
this.incorrect = true;
}
//the correct/incorrect h2s show and then this method should clear for the
//next question
setTimeout(this.handleNextQuestion, 2000);
}
Here is the handleNextQuestion method : 这是handleNextQuestion方法:
handleNextQuestion() {
//setting these properties should connect with the ngIf on the h2's and
//hide them, but its not doing that.
this.correct = null;
this.incorrect = null;
this.counter += 1;
}
The component properties correct/incorrect are on the component like this: 组件属性正确/不正确是在组件上,如下所示:
correct = null;
incorrect = null;
It's because the context of this
is lost when you do setTimeout(this.handleNextQuestion, 2000);
这是因为上下文
this
丢失,当你做setTimeout(this.handleNextQuestion, 2000);
You should change it to: 您应该将其更改为:
setTimeout(() => this.handleNextQuestion(), 2000);
As the arrow functions will bind the context 由于箭头功能将绑定上下文
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.