ngModel in select tag - inside ngFor

itaiif picture itaiif · Jul 26, 2017 · Viewed 9.2k times · Source

the ngModel in this example is killing my browser. any ideas how to get each table cell ng-model?? (i tried to use (change), and it worked - but changed the selected value)

<tr *ngFor="let step of procSteps; let i = index;  let first = first; let last = 
                                      last; let even = even; let odd = odd;">

                <td> <p>{{step.position}}</p> </td>

                <td> <p>{{step.name}}</p> </td>

                <td>
                    <select [(ngModel)]="selectedSystemStep[i]">
                        <option *ngFor="let system of systemModuleList" 
                                [value]="system.id">{{system.name}}</option>
                    </select>
                </td> 
</tr>

Answer

AJT82 picture AJT82 · Jul 26, 2017

EDIT:

Depending on your requirements, you could also add a new property to objects in your existing array, which stores the value from the dropdown to each object, something like:

<tr *ngFor="let step of procSteps; let i = index">
  <td> <p>{{step.position}}</p> </td>
  <td>
    <select [(ngModel)]="step.newProp">
      <option *ngFor="let system of systemModuleList" 
        [value]="system.id">{{system.name}}</option>
      </select>
  </td> 
</tr>

Demo for both the above and below solution: http://plnkr.co/edit/24rEpkTYKcXvMUMAyU2B?p=preview


ORIGINAL ANSWER:

How about a helper array where you store the id's?

idArr = []

In template we use the index of the iteration of items and store the obj.id to the corresponding indexes:

<div *ngFor="let item of items; let i = index">  
  <select [(ngModel)]="idArr[i]">  
    <option *ngFor="let obj of objects" [value]="obj.id">{{obj.name}}</option>  
 </select>  
</div> 

Now you neatly have all the id's stored in the idArr.