简体   繁体   English

单击 ionic 4 中的硬件后退按钮关闭 ionic-datepicker

[英]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:我在应用程序中使用ionic-datepicker (ionic v-4),以下是template代码:

<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.单击cancel/done按钮单击外部后, datepicker (即离子日期时间)将关闭。 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但这对我不起作用,我遵循了这个解决方案

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 .注意: ion-datetimeopen没有close api方法 So there are some tricks mentioned here :所以这里提到一些技巧:

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

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

Answer回答

This is already handled by default as part of the Ionic 4 code.这已经作为 Ionic 4 代码的一部分默认处理了。

What you need to do to get this functionality though is to set backdropDismiss to true.不过,要获得此功能,您需要做的是将backdropDismiss设置为 true。

Theory理论

Ionic registers a custom event ionBackButton for handling the hardware back button press: Ionic 注册了一个自定义事件ionBackButton来处理硬件后退按钮按下:

And the overlay code that manages all overlays in Ionic registers an event handler for this ionBackButton event, which dismisses the topmost overlay:并且在 Ionic 中管理所有覆盖的覆盖代码为这个ionBackButton事件注册了一个事件处理程序,它ionBackButton了最顶层的覆盖:

However, it only does this when backdropDismiss is also set to true:但是,只有当backdropDismiss也设置为 true 时,它​​才backdropDismiss

if (lastOverlay && lastOverlay.backdropDismiss) {

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编辑:建议使用布尔值来知道是否打开

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM