[SOLVED] How to preselect ion-picker items?

Hi there,

on Ionic 4 I’m trying to preselect items on the <ion-picker> before it shows up.

Following code shows the regular way of creating and showing up the picker (it’s allmost the same way like the AlertController).

import { PickerController } from '@ionic/angular';

      constructor(private pickerCtrl: PickerController) {}

      ...
      const pickerCtrl = await this.pickerCtrl.create({
        ...
        columns: [
            {
              name: 'myColumn',
              options: [
                {
                  text: 'A',
                  value: 'A',
                  selected: false
                },
                {
                  text: 'B',
                  value: 'B',
                  selected: true
                }
              ]
            },
            ...
        ]
        ...
        await pickerCtrl.present();


      });

There you can see, I initialize the columns with the B-item preselected. But when the picker shows up, the A-item got the selected: true and the B-item changed to selected: false. Even setting the selected-properties of the items AFTER creation and shownes of the picker it still does not change the selection. Every time the picker starts with the first column items.

Please … how do I accomplish the preselection of an ion-picker?

Can you share me any docs where you could pass selected as an option? I can’t find it in this doc https://ionicframework.com/docs/api/picker

No, there are NO docs :frowning: But the interfaces are explaining … (found in node_modules\@ionic\core\dist\types\components\picker\picker-interface.d.ts)

export interface PickerOptions {
    columns: PickerColumn[];
    buttons?: PickerButton[];
    cssClass?: string | string[];
    backdropDismiss?: boolean;
    animated?: boolean;
    mode?: Mode;
    keyboardClose?: boolean;
    id?: string;
    enterAnimation?: AnimationBuilder;
    leaveAnimation?: AnimationBuilder;
}
export interface PickerButton {
    text?: string;
    role?: string;
    cssClass?: string | string[];
    handler?: (value: any) => boolean | void;
}
export interface PickerColumn {
    name: string;
    align?: string;
    selectedIndex?: number;
    prevSelected?: number;
    prefix?: string;
    suffix?: string;
    options: PickerColumnOption[];
    cssClass?: string | string[];
    columnWidth?: string;
    prefixWidth?: string;
    suffixWidth?: string;
    optionsWidth?: string;
    refresh?: () => void;
}
export interface PickerColumnOption {
    text?: string;
    value?: any;
    disabled?: boolean;
    duration?: number;
    transform?: string;
    selected?: boolean;
}

Fair enough. I am unable to produce your issue at my end. Can you share a plunkr of your ionic code so that I could give it a try.

OMG why did’nt I saw this before???

Here is the solution, how to preselect some Items AFTER creating the instance and BEFORE showing up with the .present() method:

Do you see the selectedIndex property in the PickerColumn interface (whatch two posts above)? THAT one property I have to modify, if I want to preselect items in columns.

Here some code for you :slight_smile:

  showPricePicker() {

    let columns = [
      {
        name: 'Euro',
        cssClass: 'euro-class',
        options: []
      },
      {
        name: 'Komma',
        cssClass: 'komma-class',
        options: []
      },
      {
        name: 'Cent',
        cssClass: 'cent-class',
        options: []
      },
    ];



    for (let euroCounter = 0; euroCounter < 100; euroCounter++) columns[0].options.push({
      text: euroCounter.toString(),
      value: euroCounter
    });

    columns[1].options.push({
      text: ',',
      value: undefined
    });

    for (let centCounter = 0; centCounter < 100; centCounter++) columns[2].options.push({
      text: centCounter<10?'0'+centCounter.toString():centCounter.toString(),
      value: centCounter
    });




    let presentAlertConfirm: Function = async(ok: Function = (price: number) => {}, cancel: Function = () => {}) => {
      const pickerCtrl = await this.pickerCtrl.create({
        buttons: [{
          text: 'Abbrechen',
          role: 'cancel',
          cssClass: 'secondary',
          handler: () => {
            cancel();
          }
        }, {
          text: 'OK',
          handler: (price) => {
            ok(price.Euro.value + price.Cent.value / 100);
          }
        }],
        columns: columns 
      });

      // pickerCtrl.columns[0].selectedIndex = 3; // Here's the magic
      // pickerCtrl.columns[2].selectedIndex = 4;

      let euro: number = ~~this.currentProduct.price;
      let cent: number = ~~((this.currentProduct.price - euro) * 100);
      pickerCtrl.columns[0].selectedIndex = euro < 100 ? euro : 99;
      pickerCtrl.columns[2].selectedIndex = cent;

      await pickerCtrl.present();
    }

Sorry, I was too lazy to simplify the code. It just builds a columns json object, the for loops fill the columns with integers, after that the picker got instanciated, preselected and showing up at next step.

Have a nice day :slight_smile: