Mihai Miulescu
Mihai Miulescu

Reputation: 11

dynamically select option ionic 2

I have 2 select in ionic 2 and i am able to dynamically populate the second based on the value selected in first. but i cannot set the selected default option after the population. i tried:

<ion-item>
    <ion-label>City</ion-label>
    <ion-select  (ionChange)="setCity($event)">
      <ion-option selected >City1</ion-option>
      <ion-option >City2</ion-option>
    </ion-select>
  </ion-item>

  <ion-item>
    <ion-label>Zona</ion-label>
    <ion-select >
      <ion-option  *ngFor ="let location of locations[city]" 
                 [selected] = location.selected >
        {{location.zone}}
      </ion-option>
    </ion-select>
  </ion-item>

 in .ts

 this.locations = {'City1':[{ zone: 'Zone1', selected: true},{zone:'Zone2', selected: false}],
                  'City2': [{zone: 'Zone3', selected: false} {zone:'Zone4', selected: true}]}

 setCity(event){
    this.city = event;
 }

there is no selected value after the second ion-select is populated

thank you.

Upvotes: 0

Views: 1781

Answers (2)

rahul patel
rahul patel

Reputation: 434

Create a change event handler on the first select element. Then have that call a method, passing the selected value with it. Then do some checks on the selected values to determine if you want to show the next select and then the list.

Check out this StackOverflow question How to show second dropdown data based on previous dropdown selection

Working version: https://embed.plnkr.co/Qu1lL6PDIX2DTDGv01ZI/

UPDATE Display Default selected item

You wanna display Default selected item then you need to add these few line in your html page

like that:

     <ion-label>District</ion-label>
 <ion-select (ionChange). ....
     <ion-option [value]="0" >select District</ion-option>
      <ion-option [value]="sDistrict" *ngFor = ...
</ion-select>

and add these line in your type script(.ts) file

export class HomePage {
 ....
sState: number = "0";
sDistrict: number = "0";
.....
}

if you face any problem then let me know.

Upvotes: 0

Sathyajith
Sathyajith

Reputation: 4024

Try setting the ngModel attribute in ion-select and value attribute in ion-option like below

<ion-label>Zona</ion-label>
<ion-select [(ngModel)]="mLocation" >
  <ion-option [value] = "location" *ngFor ="let location of locations[city]" 
             [selected] = location.selected >
    {{location.zone}}
  </ion-option>
</ion-select>

Upvotes: 0

Related Questions