Loading Posts...

How to Present a Picker Using the Ion Picker Component

How to Present a Picker Using the Ion Picker Component

Almost unnoticed since Ionic 4 we have a great, maybe underrated new component named ion-picker which allows us to display exactly what you might wish: A picker!

While in the past you had to use a native Cordova plugin to create such a picker component with multiple columns, now you can actually use the new picker.

ionic-4-picker-component

The only problem is the documentation is quite sparse at the moment of writing this, so here’s what you need to know about using this cool new component!

Adding the Picker Component

I skipped starting the blank new app command in this Quick win because at this point you should know how to do it. Also, we don’t need any additional packages as everything is already there!

The picker can be used easily from code using the Picker Controller, so we don’t need any specific markup items and can simply call it from a button.

In our example we want to create 2 different pickers, one basic and one a bit more advanced. Both will simply fill some values that we can then display in the view for testing, so our view doesn’t really have a lot to do with the actual picker.

Therefore, go ahead and change the app/home/home.page.html to:


  
    
      Ionic Picker
    
  




  
    Framework: 
    {{ framework }}
    Select
  


  
    Game
    Category
    Rating
  

  
    {{ selected[0] }}
    {{ selected[1] }}
    {{ selected[2] }}
  

  Show Advanced Picker

Alright, now we can move on to the real picker fun!

The two versions we want to display should reflect:

  • Basic: A simple picker with one column to select from
  • Advanced: A picker with 3 columns and different values plus additional styling

You can check out the documentation of the picker for all the information about it, or, as I also recommend, simply dive into the TypeScript definition files when you use the controller from your IDE.

There you will have it super easy to find which values you can or need to pass to the picker in order to create it to your needs!

For the basic picker you just need to define the buttons to close it again plus the columns and the values you want to display in the column. Make sure you keep an eye on the async returns of the picker (or in general Ionic overlay components) since version 4!

Once the picker is dismissed we can access it and grab the right values which are buried a bit in the data, but again, looking up in the TS definition helps a lot here!

Let for now already add the code to our app/home/home.page.ts:

import { Component } from '@angular/core';
import { PickerController } from '@ionic/angular';
import { PickerOptions, PickerButton } from '@ionic/core';

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {

  framework = '';
  selected = ['','',''];

  constructor(private pickerCtrl: PickerController) { }

  async showBasicPicker() {
    let opts: PickerOptions = {
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Done'
        }
      ],
      columns: [
        {
          name: 'framework',
          options: [
            { text: 'Angular', value: 'A' },
            { text: 'Vue', value: 'B' },
            { text: 'React', value: 'C' }
          ]
        }
      ]
    };
    let picker = await this.pickerCtrl.create(opts);
    picker.present();
    picker.onDidDismiss().then(async data => {
      let col = await picker.getColumn('framework');
      this.framework = col.options[col.selectedIndex].text;
    });
  }

  async showAdvancedPicker() {
    let opts: PickerOptions = {
      cssClass: 'academy-picker',
      buttons: [
        {
          text: 'Cancel',
          role: 'cancel'
        },
        {
          text: 'Done',
          cssClass: 'special-done'
        }
      ],
      columns: [
        {
          name: 'game',
          options: [
            { text: 'Dota', value: 'dota' },
            { text: 'WoW', value: 'wow' },
            { text: 'CS', value: 'cs' }
          ]
        },
        {
          name: 'category',
          options: [
            { text: 'MOBA', value: 'MOBA' },
            { text: 'MMORPG', value: 'MMORPG' }
          ]
        },
        {
          name: 'rating',
          options: [
            { text: 'Good', value: 1 },
            { text: 'Very Good', value: 2 },
            { text: 'Excellent', value: 3 }
          ]
        }
      ]
    };
    let picker = await this.pickerCtrl.create(opts);
    picker.present();
    picker.onDidDismiss().then(async data => {
      let game = await picker.getColumn('game');
      let cat = await picker.getColumn('category');
      let rating = await picker.getColumn('rating');
      this.selected = [
        game.options[game.selectedIndex].text, 
        cat.options[cat.selectedIndex].text,
        rating.options[rating.selectedIndex].text
      ];
    });
  }
}

The advanced picker does pretty much the same, but now we define multiple picker columns and also additional CSS classes to style the picker.

Getting the values is again basically the same, you just need to use the right column name to get the data from the picker and then use the selectedIndex to get the actual entry (and then get the text or value from it).

One small issue that might arise now is that you can’t put your custom CSS in the file for the page – simply because the picker component lives at a different level in the view hierarchy!

Using Custom CSS

In order to write custom CSS for the CSS classes you added to the advanced picker we need to add it at a higher level in our app. You can also see that your CSS class was added when you inspect the picker component in your browser:

ionic-picker-custom-class

Now a good place to put your CSS for a picker (or also modal!) is at the app/app.scss, so insert a few lines of CSS below the already existing imports:

.special-done {
    font-weight: 600 !important;
    color: #fff !important;
}

.academy-picker {
    --background: #88bdff;
    --ion-text-color: #fff;
    .picker-opt-selected {
        color: red;
    }
}

Now your picker gets the custom (very ugly) styling applied, but you get a sense of how to control the UI and make it fit exactly the needs of your project!

Conclusion

The new Ionic picker component is a great alternativ to using an additional Cordova plugin and works out of the box without any additional packages. While the docs are a bit thin on it now, I’m sure we’ll see more information and great use cases for this component in the near future!

You can also find a video version of this Quick Win below.

The post How to Present a Picker Using the Ion Picker Component appeared first on Ionic Academy.

user

The author didnt add any Information to his profile yet

Loading Posts...
WP2FB Auto Publish Powered By : XYZScripts.com