SGR
SGR

Reputation: 2417

To close ionic-datepicker on clicking hardware back button in ionic 4

I am using ionic-datepicker in the app(ionic v-4), Below is the template code:

<ion-datetime  formControlName="meeting_date" display-format="MMM DD, YYYY"></ion-datetime>

The datepicker(i,e ion-datetime) will close after clicking cancel/done button or on clicking outside.But it not closing on clicking hardware back button.

In the page where i am used datepicker, I tried like this:

ionViewWillLeave(){
        let backDrop: any = document.getElementsByTagName('ion-picker-cmp');
        if(backDrop.length > 0){
            for(let i = 0; i< backDrop.length; i++){
                backDrop[i].style.display = 'none';
            }
        }
      }

But it didn't worked for me, I followed this solution

Upvotes: 4

Views: 2453

Answers (3)

Kingdox
Kingdox

Reputation: 1

This worked to me:

    constructor(
    public pickerCtrl: PickerController,

...and

ionViewWillLeave(){
this.pickerCtrl.dismiss();

EDIT: Recomend use a boolean to know whether is opened or not

Upvotes: 0

rtpHarry
rtpHarry

Reputation: 13125

Answer

This is already handled by default as part of the Ionic 4 code.

What you need to do to get this functionality though is to set backdropDismiss to true.

Theory

Ionic registers a custom event ionBackButton for handling the hardware back button press:

And the overlay code that manages all overlays in Ionic registers an event handler for this ionBackButton event, which dismisses the topmost overlay:

However, it only does this when backdropDismiss is also set to true:

if (lastOverlay && lastOverlay.backdropDismiss) {

Upvotes: 0

Vahid Najafi
Vahid Najafi

Reputation: 5243

First you should know whether it's focused or not, so:

<ion-datetime #dateTime (ionFocus)="onDateFocused()" formControlName="meeting_date" display-format="MMM DD, YYYY"></ion-datetime>

And in component:

onDateFocused() {
  this.focused = true; // make it false in on blur
}

Then register to hardware back button:

this.platform.backButton.subscribe(() => {
  // this does work
});

Note: There is no close api method for ion-datetime as well as open. So there are some tricks mentioned here:

@ViewChild("dateTime", {static: false}) dateTime : DateTime;

ngOnInit() {
  this.platform.backButton.subscribe(() => {
    this.dateTime._picker.dismiss();
  })
}

Upvotes: 1

Related Questions