AngularNewbie
AngularNewbie

Reputation: 133

Pushing a value in array does not display in View angular

I'm trying to display the incorrect answers made by the user on a specific quiz. But it does not display the data in my HTML. What am I doing wrong in here?

on my 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>

on my typescript:

 wrongAnswers: any[] = [];


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

On my console this is what is being displayed:

enter image description here

Upvotes: 0

Views: 2028

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222722

You are trying to push array to already existing array, if you really want to do that use concat instead

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

if you want to push one object, remove the [] , so that object will be pushed

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

Upvotes: 2

cyr_x
cyr_x

Reputation: 14267

The array reference isn't changing when using Array.prototype.push, therefore the angular changedetection isn't aware of the changes.

And also you were pushing an array into you array not a simple object.

Use Array.prototype.concat to create a new reference when adding an item to the array:

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

Upvotes: 0

Related Questions