user3738290
user3738290

Reputation: 445

Data binding <select> element's selected index with Angular

Could I please ask what I am doing wrong in the following:

Firstly, the following works fine:

I have the following variables in my .ts component:

public m_array = ["one", "two", "three", "four"];
public m_selectedValueIndex = "two";

and in my html I have:

<select [(ngModel)]="m_selectedValueIndex">

    <option *ngFor = 'let num of m_array'>
        {{num}}
    </option>

</select>

All works fine, and I can see that I have two-way binding on m_selectedValueIndex.

But If I change to the code below things do not work as I expected they would:

.TS code:

public m_array = ["one", "two", "three", "four"];
public m_selectedValueIndex = 2; // THIS IS NOW A NUMBER

html code:

<select [(ngModel)]="m_array[m_selectedValueIndex]"> // THIS IS NOW AN INDEX TO ARRAY

    <option *ngFor = 'let num of m_array'>
        {{num}}
    </option>

</select>

Initially it looks like it's working because the initially selected item is indeed the one with and index of m_selectedValueIndex. But if I use the list box then the values listed actually change.

I may initially have:

one two three four

(where italics indicates that it is selected). This is as I would expect because m_selectedValueIndex = 2.

But if I click on any item (say "four" for example) then the listbox contents change to:

one two four four

i.e. it is replacing item at index m_selectedValueIndex with my selection. Also the value of m_selectedValueIndex remains 2.

Just wanted to see if I could bind by index instead of value.

Thanks for any help.

Upvotes: 0

Views: 862

Answers (1)

Amer
Amer

Reputation: 6706

You need to bind the option value to the array's index using [value]="ndx", (after defining it using let ndx = index within *ngFor) like the following:

<select [(ngModel)]="m_selectedValueIndex"> // THIS IS NOW AN INDEX TO ARRAY

  <option *ngFor="let num of m_array; let ndx = index" [value]="ndx">
    {{ num }}
  </option>
</select>

Upvotes: 2

Related Questions