augeres
augeres

Reputation: 71

Array with select option in Angular and Typescript

I display 51 questions with their related answers on a page. Both information come from one web-service call.

<tbody>
   <tr *ngFor="let QuestionOption of questions; trackBy: trackQuestionById; let i = index;">
   <th scope="row">{{QuestionOption.id}}</th>
   <td>{{QuestionOption.name}} {{QuestionOption.description}}
    </p>
     <select  class="form-control"  name="selectAnswer" [(ngModel)]="answer[i]">
     <option *ngFor="let answers of QuestionOption.Answers" [ngValue]="answers.id">{{answers.description}}</option>
    </p>
   </td>
</tr>
</tbody>

on the typescript code I try the following:

answer: Answer[];
this.answer = new Array<Answer>();

The type Answer has multiple fields like: Id, Name, Score, Description

What is not working is that I always have get the Id into the answer[i] but I want to have the id in the field answer[i].id

If i change the

[(ngModel)]="answer[i]"

into

[(ngModel)]="answer[i].id"

I get the following exception: ERROR TypeError: "_co.caaAnswer[_v.context.index] is undefined"

I also tried:

[(ngModel)]="answer[i]?.id"

So is it correct to use answer[i] ? and then in the option I should somehow assign to answer[i].id the selected value. If so somebody can help how to do it.

Any help is appreciated! Thanks a lot. augeres

Upvotes: 2

Views: 21032

Answers (2)

augeres
augeres

Reputation: 71

I found the solution. The problem was that the compareWith function did not work properly because of the Array. It only works in case you name the html select based upon the array index:

Working version:

<select class="form-control" id="field_answer{{i}}" name="field_answer{{i}}" [(ngModel)]="resultAnswer[i].answer" [compareWith]="compareFn">
<option [ngValue]="answer" *ngFor="let answer of Question.answers; trackBy: trackAnswerById">{{answer.id}} {{answer.description}}</option>
</select> 

Upvotes: 4

Fahad Subzwari
Fahad Subzwari

Reputation: 2325

You have to push into answer on select change like this

<select  class="form-control"  name="selectAnswer" [(ngModel)]="selectedAnswerId" (change)="setAnswer(i)">
 <option *ngFor="let answers of QuestionOption.Answers" [ngValue]="answers.id">{{answers.description}}</option>
<select>

in component.ts

selectedAnswerId : number;
setAnswer(index){
  this.answer[index].push({id : this.selectedAnswerId})
}

Upvotes: 0

Related Questions