AngularMaterial对话框/叠层有时需要在关闭后点击DOM。
创始人
2024-10-28 09:01:39
0

在使用Angular Material的对话框或叠层时,有时关闭后还需要点击一下DOM才能使背景遮罩消失。这通常是由于仍然存在某些已注销的DOM事件监听器所致。为了解决这个问题,您可以在关闭对话框或叠层时手动注销事件监听器。

以下是一个示范:

import { Component, OnInit, OnDestroy, AfterViewInit, ViewChild, ElementRef } from '@angular/core';
import { MatDialog } from '@angular/material';

@Component({
  selector: 'app-example-dialog',
  templateUrl: './example-dialog.component.html',
  styleUrls: ['./example-dialog.component.css']
})
export class ExampleDialogComponent implements OnInit, OnDestroy, AfterViewInit {
  private clickListener: any;

  constructor(private dialog: MatDialog) { }

  ngOnInit() {
  }

  ngAfterViewInit() {
    // NOTE: we need to add a short delay before adding the click listener to ensure the initialization of the dialog's backdrop element
    //       adding the click listener with no delay might fail silently and do nothing, even if the backdrop element already exists
    setTimeout(() => {
      const backdrop = document.querySelector('.cdk-overlay-backdrop');
      if (backdrop) {
        this.clickListener = () => {
          this.dialog.closeAll();
          this.removeBackdropClickListener();
        };
        backdrop.addEventListener('click', this.clickListener);
      }
    }, 200);
  }

  ngOnDestroy() {
    this.removeBackdropClickListener();
  }

  private removeBackdropClickListener() {
    const backdrop = document.querySelector('.cdk-overlay-backdrop');
    if (backdrop && this.clickListener) {
      backdrop.removeEventListener('click', this.clickListener);
      this.clickListener = null;
    }
  }
}

在这个示例中,我们在对话框初始化后添加了一个按键事件监听器。在这个监听器中,我们先注销了所有正在运行的对话框,然后移除了背景遮罩元素上的事件监听器。如此一来,关闭对话框或叠层后,它们的背景遮罩就会立刻消失,不需要再次点击DOM。

相关内容

热门资讯

透视操作!wepoker辅助器... 透视操作!wepoker辅助器软件下载(AApoker辅助)确实真的有辅助神器(哔哩哔哩)1、wep...
透视大纲!有哪些免费的wpk作... 透视大纲!有哪些免费的wpk作必弊码(HHpoker必备)确实是有辅助神器(哔哩哔哩)1、用户打开应...
透视窍要!epoker透视底牌... 透视窍要!epoker透视底牌(HHpoker安装包)其实真的是有辅助插件(哔哩哔哩)1、epoke...
透视妙计!wepoker透视脚... 透视妙计!wepoker透视脚本是什么(HHpoker德州)本来真的是有辅助app(哔哩哔哩)1、点...
透视妙计!we poker辅助... 透视妙计!we poker辅助器下载(WePoKer数据)果然真的有辅助脚本(哔哩哔哩)1、打开软件...
透视窍门!wpk俱乐部辅助器(... 透视窍门!wpk俱乐部辅助器(HHpoker教程)真是是真的有辅助app(哔哩哔哩)小薇(辅助器软件...
透视手段!佛手大菠萝辅助(AA... 透视手段!佛手大菠萝辅助(AApoker靠谱)都是真的有辅助脚本(哔哩哔哩)小薇(辅助器软件下载)致...
透视教程书!wpk软件是正规的... 透视教程书!wpk软件是正规的吗(HHpoker下载)确实是有辅助技巧(哔哩哔哩)1、起透看视 wp...
透视阶段!wepoker买脚本... 透视阶段!wepoker买脚本靠谱吗(WePoKer新版本)确实存在有辅助插件(哔哩哔哩)1、wep...
透视指南!wepoker透视方... 透视指南!wepoker透视方法(HHpoker机器人)一直真的是有辅助攻略(哔哩哔哩)1、玩家可以...