Ionic ion-datetime时间滚轮点击背景及默认按钮无法关闭求助
问题解决:ion-datetime无法关闭导致页面卡死
问题根源
你手动嵌套了<ion-popover>标签,破坏了ion-datetime-button的默认关联逻辑,导致弹出层的关闭事件无法正确触发,点击背景或按钮都没法关闭弹窗,最终页面卡死。
修复方案
直接移除手动添加的ion-popover,让ion-datetime-button自动管理弹出层,把ion-datetime放在页面隐藏区域即可。修改后的完整代码如下:
<ng-template #INTERVALS> <ion-header> <ion-toolbar> <ion-col size="12" slot="start" > <ion-text class="ion-margin-start ion-text-size-20 ion-text-weight-500">{{ 'new_time_slot' | translate }}</ion-text> </ion-col> </ion-toolbar> </ion-header> <ion-content class="ion-padding"> <form [formGroup]="intervalForm"> <ion-item> <ion-label>{{ 'description' | translate }}</ion-label> <ion-input formControlName="description" slot="end" class="ion-text-right" ></ion-input> </ion-item> <ion-item> <ion-label>{{ 'price_list' | translate }}</ion-label> <ion-select formControlName="priceList"> <ion-select-option *ngFor="let priceLevel of priceLevelList" [value]="priceLevel?.name" > {{ priceLevel?.name }} </ion-select-option> </ion-select> </ion-item> <ion-item> <ion-label>{{ 'slot_color' | translate }}</ion-label> <ion-input></ion-input> </ion-item> <ion-item lines="none" class="ion-margin-top" > <ion-label class="ion-text-uppercase">{{ 'interval_time' | translate }}</ion-label> </ion-item> <ion-item> <ion-label>{{ 'from' | translate }}</ion-label> <ion-datetime-button datetime="fromtime"></ion-datetime-button> </ion-item> <ion-item> <ion-label>{{ 'to' | translate }}</ion-label> <ion-datetime-button datetime="totime"></ion-datetime-button> </ion-item> <!-- 把datetime放在隐藏区域,保持和button的id关联 --> <ion-datetime hidden id="fromtime" #fromtime hourCycle="h23" presentation="time" value="{{ intervalFrom }}" (ionChange)="timeChange('from', fromtime.value)" > <ion-buttons slot="buttons"> <ion-button color="primary" (click)="$event.target.closest('ion-popover')?.dismiss()" > Done </ion-button> </ion-buttons> </ion-datetime> <ion-datetime hidden id="totime" #totime hourCycle="h23" presentation="time" min="{{ intervalFrom }}" value="{{ intervalTo }}" (ionChange)="timeChange('to', totime.value)" [showDefaultButtons]="true" ></ion-datetime> </form> </ion-content> <ion-footer class="ion-padding ion-no-border ion-text-right"> <ion-button color="danger" (click)="modalCtrl.dismiss(data)" > {{ 'cancel' | translate }} </ion-button> <ion-button color="danger" (click)="onSubmit(intervalForm.value)" > {{ 'add' | translate }} </ion-button> </ion-footer> </ng-template>
关键修改点
- 删掉了每个
ion-datetime-button对应的手动ion-popover,让组件自动处理弹出层的创建和关闭 - 将
ion-datetime移到ion-content内,用hidden属性隐藏,保持和按钮的datetime属性关联(id匹配) - 自定义的Done按钮通过
$event.target.closest('ion-popover')?.dismiss()直接找到父级popover并关闭,替代原来的DismissClick方法(原来的方法可能没正确获取到popover实例) - 保留了
showDefaultButtons="true"的datetime默认按钮,现在点击默认按钮或弹出层背景都能正常关闭
内容的提问来源于stack exchange,提问作者mdecrema
相关产品推荐
相关产品推荐

