Date picker popup in Ionic 6

January 7th 2022 Ionic 4+

Fortunately, there are not too many breaking changes in Ionic 6. The one that impacted the applications that I had to update to Ionic 6 was the redesign of the date picker. Although it was easy to make the markup compatible with Ionic 6, the new component broke the existing design.

Here is a typical markup for a date picker in Ionic 5:

<ion-item>
  <ion-label>Pick date</ion-label>
  <ion-datetime
    displayFormat="DD.MM.YYYY"
    presentation="date"
    [(ngModel)]="date"
  ></ion-datetime>
</ion-item>

This causes the date picker control to display only the selected date, but the picker opens as a popup:

To make the markup compatible with Ionic 6, the displayFormat attribute must be removed as it is no longer supported:

<ion-item>
  <ion-label>Pick date</ion-label>
  <ion-datetime presentation="date" [(ngModel)]="date"></ion-datetime>
</ion-item>

The displayFormat attribute has been removed for good reason. It no longer has any meaning as the picker is now rendered inline and the date no longer needs to be formatted:

Inline date picker in Ionic 6

As I mentioned earlier, this change completely ruins the layout of any page that uses a date picker. Fortunately, there is a way to show the date picker in a popup by just changing the markup, using the ion-popover component:

<ion-item>
  <ion-label>Pick date</ion-label>
  <ion-input
    value="{{ date | date: 'dd.MM.yyyy' }}"
    id="date"
    class="ion-text-end"
  ></ion-input>
  <ion-popover trigger="date" size="cover">
    <ng-template>
      <ion-datetime
        presentation="date"
        [(ngModel)]="date"
        locale="sl-SI"
      ></ion-datetime>
    </ng-template>
  </ion-popover>
</ion-item>

To make the ion-datetime component appear in a popup, place it inside the ion-popover component. To display the selected date on the page, a regular ion-input component is used. The following is worth mentioning:

To open the popup when the input is clicked, only two things are required:

  • The ion-input element needs an id attribute (date in the above snippet).
  • The trigger attribute of the ion-popover element needs to be set to the same value.

The resulting behavior is now very similar to Ionic 5:

You can view the full code for both Ionic 5 and Ionic 6 date picker in my GitHub repository.

Ionic 6 introduced a breaking change to the date picker. Instead of being a popup like in Ionic 6, it is now rendered inline. The ion-popover component can be used to achieve similar behavior to Ionic 5, so that the layout of pages with a date picker is not broken when upgrading to Ionic 6.

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

Copyright
Creative Commons License