Quan Huynh
Quan Huynh

Reputation: 63

how to bind ngmodel to select option within an ngfor

(I haven't been able to find a similar question to this on StackOverflow, if I missed anything please link me) I have an ngfor loop looping over a list of records. Each record have multiple actions (edit, delete, etc.) in a select list. I want to be able to select an action that only applies to the record.

<tr *ngFor="let rec of records">

    <td><a href=""> {{rec.name}} </a></td>
    <td>{{rec.description}}</td>
    <td><a href=""> {{rec.date}} </a></td>
    <td>
        <select [(ngModel)]="selected" (change)="changeOption(rec);">
            <option selected disabled>Actions</option>
            <option value="editRec">Edit Record</option>
            <option value="deleteRec">Delete Record</option>
            ...more options
        </select>
    </td>
</tr>

changeOption right now just simply prints out this.selected, but whenever the ngModel is changed, the screen shows that select values for ALL records are changed (so they ALL show edit/delete/etc. whenever something is selected).

this is ok in the component file since i still know which record and which action are selected, but UI-wise it looks strange. i think this is expected behavior since every select value is bound to this ngModel, but i'd like to know if it's possible to bind individually?

Upvotes: 2

Views: 2438

Answers (1)

developer033
developer033

Reputation: 24894

It's happening because you're using a primitive variable in your [(ngModel)] inside *ngFor.. so every bind will reference the same variable (in this case selected). To solve this, you can change ngModel to rec.selected:

<select [(ngModel)]="rec.selected" (change)="changeOption(rec)">...

PLUNKER

Upvotes: 2

Related Questions