Search code examples
angularionic-frameworkionic5

Ionic 5: DateTime does not work inside SegmentButton


I tried to place an ion-datetime element inside ion-segment-button. This was done to simulate a choice of date between "today", "yesterday" and a custom date. The code looked like this:

<ion-segment mode="md" [(ngModel)]="dateSegment">
  <!-- Other buttons -->
  <ion-segment-button value="OTHER" color="primary">
    <ion-datetime [(ngModel)]="selectedDate"></ion-datetime>
  </ion-segment-button>
</ion-segment>

However, the date picker did not show up when clicking the button.


Solution

  • I eventually implemented a workaround by opening the DateTime on button click via @ViewChild as described here:

    In template:

    <ion-segment-button value="OTHER" (click)="openDateTime()">
      <ion-datetime #dateTime [(ngModel)]="selectedDate"></ion-datetime>
    </ion-segment-button>
    

    In component:

    export class MyComponent {
    
      @ViewChild('dateTime', { static: true }) dateTime: IonDatetime;
    
      openDateTime() {
        this.dateTime.open();
      }
    }