Mihaly
Mihaly

Reputation: 301

how can i bind to a specific array item in angular 2?

I want to use data that has been set in an array to bind to specific input boxes. with this piece of code, I get an error:

Recommendation.question contains an array of questions that has been loaded through a service. This works fine, and also if just show the value of question by using the brackets it works. Just the value of the array won't bind to the input box.

The error I Get:

Unhandled Promise rejection: Cannot assign to a reference or variable! ; Zone: <root> ; Task: Promise.then ; Value: ZoneAwareError Error: Cannot assign to a reference or variable!

  <div class="list-group-item"
    *ngFor="let question of Recommendation.question; let i = index;">
    <input class="form-control" name="question" [(ngModel)]="question"/>
    {{question}}
    {{i}}
  </div>

if I comment out the input field, the {{question}} shows the correct value that is at the current index of the array.

Upvotes: 0

Views: 1309

Answers (1)

AVJT82
AVJT82

Reputation: 73337

The problem should lie with that the [(ngModel)] variable is the same as the reference in the iteration, meaning question.

Doing this should work:

<div class="list-group-item"
  *ngFor="let question of Recommendation.question; let i = index;">
  <input class="form-control" name="question" [(ngModel)]="Recommendation[i]"/>
  {{question}}
  {{i}}
</div>

Upvotes: 1

Related Questions