Ion-select does not show selected option when value is an object type

2.9k views Asked by At

I am binding an object to the value property of select-option.

 <ion-item>
    <ion-label>Choose</ion-label>
    <ion-select [value]="{key:'abc',value:'ABC'}">
      <ion-select-option value="{key:'abc',value:'ABC'}">ABC</ion-select-option>
      <ion-select-option value="{key:'pqr',value:'PQR'}">PQR</ion-select-option>
      <ion-select-option value="{key:'xyz',value:'XYZ'}">XYZ</ion-select-option>
    </ion-select>
  </ion-item>

When popup opens it does not show the selected value.

Click here to view the image

1

There are 1 answers

0
Pankaj Sati On

Your data bindings are failing because the value property in ion-select-option holds a string, while the value property of ion-select holds an object.

You need to bind the value property of ion-select-option.

<ion-select-option [value]="{key:'abc',value:'ABC'}">ABC</ion-select-option>

I would recommend that you should not use the objects as value of ion-select-option.

Since, there is key & value in your object, you should make a more clear code. Keep the key part in value attribute of ion-select-option.

<ion-item>
    <ion-label>Choose</ion-label>
    <ion-select [(ngModel)]="myKey">
      <ion-select-option value="abc">ABC</ion-select-option>
      <ion-select-option value="pqr">PQR</ion-select-option>
      <ion-select-option value="xyz">XYZ</ion-select-option>
    </ion-select>
  </ion-item>

In your component, declare a variable myKey and assign a value to it.

myKey='abc';

This is an example of 2-way data binding in angular. Read more here: https://codecraft.tv/courses/angular/forms/template-driven/#_two_way_data_binding