0

我正在制作一个基本的测验应用程序。每当用户回答问题时,我希望将答案确定为正确/不正确,移至下一个问题,并隐藏正确/不正确的消息。

问题:当 this.correct / this.incorrect 设置为 null/false 时,h2 正确/错误消息不会隐藏自己。

在继续下一个问题之前,我希望这些 h2 显示 2 个部分。

这是应该切换的 html 模板部分,但它们不是:

  <h2 *ngIf="correct">Correct</h2>
  <h2 *ngIf="incorrect">Incorrect! The answer is {{ questions[counter].answer }}</h2>

这是一种组件方法:

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);
}

这是 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;
}

组件属性正确/不正确在组件上,如下所示:

  correct = null;
  incorrect = null;
4

1 回答 1

3

this这是因为当你这样做时,上下文会丢失setTimeout(this.handleNextQuestion, 2000);

您应该将其更改为:

setTimeout(() => this.handleNextQuestion(), 2000);

由于箭头函数将绑定上下文

于 2018-06-25T18:21:26.493 回答