【问题标题】:Pushing a value in array does not display in View angular推送数组中的值不会在视图角度中显示
【发布时间】:2018-02-25 16:40:16
【问题描述】:

我正在尝试显示用户在特定测验中的错误答案。但它不会在我的 HTML 中显示数据。我在这里做错了什么?

在我的 html 上:

 <ion-slide *ngFor="let incorrect of wrongAnswers;let i=index">
  <ion-label>{{i+1}}</ion-label>
  <h5>{{incorrect.questionA}}</h5>
  <h5>{{incorrect.choice}}</h5>
  <h5>{{incorrect.answer}}</h5>
  <button ion-button (click)="error()"></button>
</ion-slide>

在我的打字稿上:

 wrongAnswers: any[] = [];


 if (answer.correct == false) {
  this.wrongAnswers.push([{
    questionA: question.questionText,
    choice: answer.selected,
    answer: answer.answer
  }]);
}

在我的控制台上显示的是:

【问题讨论】:

  • 尝试删除围绕您正在推送的对象的[],即.push({ ... });

标签: arrays angular typescript ionic-framework


【解决方案1】:

您正在尝试将 array 推送到现有数组,如果您真的想这样做,请改用 concat

this.wrongAnswers.concat([{
    questionA: question.questionText,
    choice: answer.selected,
    answer: answer.answer
  }]);

如果要推送一个对象,请删除 [] ,以便推送该对象

this.wrongAnswers.push({
    questionA: question.questionText,
    choice: answer.selected,
    answer: answer.answer
  });

【讨论】:

    【解决方案2】:

    使用Array.prototype.push 时数组引用没有改变,因此角度变化检测不知道这些变化。

    而且你将一个数组推入你的数组而不是一个简单的对象。

    向数组添加项时使用Array.prototype.concat 创建新引用:

    this.wrongAnswers = this.wrongAnswers.concat({
      questionA: question.questionText,
      choice: answer.selected,
      answer: answer.answer
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-29
      • 2021-06-29
      • 1970-01-01
      • 2021-03-19
      • 1970-01-01
      • 2019-03-11
      • 1970-01-01
      相关资源
      最近更新 更多