ionc4 modal (ion-modal, Modal Controller) 组件, 只能显示一次,解决方法

最近用ionic4开发,遇到使用ion-modal组件,之前用ionic3写的代码,按照官方文档 做了相应修改:

import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';
import { ModalPage } from '../modal/modal.page';

@Component({
  selector: 'app-exam-detail',
  templateUrl: './exam-detail.page.html',
  styleUrls: ['./exam-detail.page.scss'],
})
export class ExamDetailPage implements OnInit {

  constructor(
    public modalController: ModalController,
  ) {

  }
  
  ......

  async presentModal() {
    const modal = await this.modalController.create({
      component: ModalPage,
      cssClass: 'modalClass'
    });
    await modal.present();
  }

}

对于ModalPage,与ionic3的区别就是关闭的代码,由ViewController改成了ModalController:

import { Component, OnInit } from '@angular/core';
import { ModalController } from '@ionic/angular';

@Component({
  selector: 'app-modal',
  templateUrl: './modal.page.html',
  styleUrls: ['./modal.page.scss'],
})
export class ModalPage implements OnInit {

  constructor(
    public modalController: ModalController,
  ) { }

  dismiss(){
    this.modalController.dismiss();
  }
}

这样改完后,发现第一次执行 presentModal() 可以显示模态窗口,但是关闭后,再次点击就不显示了。后来搜索了半天也没发现相关资料,自己尝试后发现,只要在create时加上animated: false属性就可以解决。当然默认是有动画效果的,加上animated: false后就没有动画 效果了。至于怎么做到不影响 动画 效果还能解决再次点击不显示的问题我做到。

续:

这个问题本质是tap的点透问题,也就是类似之前tap事件在移动设备上的延迟,对于上面的这个问题,当点击按钮时弹出了模态窗口,然后延迟时间到了,系统又在刚才点击的位置触发了一下点击,于是刚刚显示的窗口层又被关闭了(因为ionic的modal组件默认是点击背影则关闭(backdropDismiss: true),于是改为backdropDismiss: false,后就解决了这个问题。但是我还是不太清楚,为什么第一次就能正常显示,可能是因为第二次打开弹层因为有缓存机制,所以创建速度更快的原因吧。

喜欢的话,请点赞,转发、收藏、评论,谢谢!
原文地址:https://www.cnblogs.com/johnjackson/p/11811010.html