Configurable Select Control in Ionic Navbar

August 17th 2018 Ionic 2/3

There are lots of components included with Ionic framework, but not many of them can be used inside a Navbar.

If you want find an out-of-the box solution for putting a select or a dropdown into the Navbar, you can for example take a look at the standalone Select component, but it wasn't designed to be put into the Navbar.

Fortunately, with some resourcefulness, it's easy enough to create a solution of your own by combining together multiple built-in components.

Select component in Ionic Navbar

To create my language selector from the image above, I first created a standard toolbar button. I included a dropdown icon in it, to give it a dropdown appearance:

<ion-header>
  <ion-navbar>
    <ion-title>
      Ionic Blank
    </ion-title>
    <ion-buttons end>
      <button ion-button icon-end (click)="changeLanguage()">
        {{language.toUpperCase()}}
        <ion-icon name="arrow-dropdown"></ion-icon>
      </button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

On button click, I show the available values to the user in a standard alert dialog with radio inputs:


changeLanguage() {
  let alertOptions: AlertOptions = {
    title: 'Language',
    inputs: [ {
      type: 'radio',
      label: 'English',
      value: 'en',
      checked: this.language == 'en'
    }, {
      type: 'radio',
      label: 'slovenščina',
      value: 'sl',
      checked: this.language == 'sl'
    } ],
    buttons: [ {
      text: 'Cancel'
    }, {
      text: 'OK',
      handler: selectedLanguage => {
        this.language = selectedLanguage;
      }
    } ]
  };
  this.alertCtrl.create(alertOptions).present();
}

It works great for a mobile application. Probably even better than a regular dropdown menu would.

Language selection in a standard alert dialog

Of course, there are ways to further improve the solution:

  • Instead of hardcoding the available languages in the alert options, you will usually have an array of supported languages as value/label pairs which you can map to the correct input options format.
  • You can expand the button handler with the additional logic required to actually change the language in the application.
  • To implement localization in the application you should look at the excellent NGX-Translate library.

Get notified when a new blog post is published (usually every Friday):

Copyright
Creative Commons License