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作必弊方法(透视)一直是有辅助安装(有挂方法)-哔哩哔哩1、下载好wepoke...
透视总结!hhpoker破解工... 透视总结!hhpoker破解工具(透视)都是是真的辅助工具(有挂方式)-哔哩哔哩1、进入游戏-大厅左...
据统计!werplan有挂吗(... 据统计!werplan有挂吗(透视)一直存在有辅助插件(揭秘有挂)-哔哩哔哩;1、玩家可以在werp...
透视玄学!拱趴大菠萝怎么开挂(... 透视玄学!拱趴大菠萝怎么开挂(透视)一贯是真的辅助修改器(有挂助手)-哔哩哔哩1、金币登录送、破产送...
透视透视!wepoker轻量版... 透视透视!wepoker轻量版书签(透视)切实有辅助平台(真的有挂)-哔哩哔哩1、wepoker轻量...
现就发布提示!wpk俱乐部有没... 现就发布提示!wpk俱乐部有没有辅助(透视)真是是有辅助app(有挂方式)-哔哩哔哩亲,关键说明,w...
据权威媒体报道!hhpoker... 据权威媒体报道!hhpoker辅助软件下载(透视)切实有辅助app(有挂猫腻)-哔哩哔哩1、任何hh...
透视好牌!wepoker辅助是... 透视好牌!wepoker辅助是真的假的(透视)真是真的是有辅助app(有挂透明挂)-哔哩哔哩运wep...
透视规律!hhpoker德州机... 透视规律!hhpoker德州机器人(透视)一贯存在有辅助神器(有挂神器)-哔哩哔哩1、玩家可以在hh...
据权威媒体报道!wepoker... 据权威媒体报道!wepoker怎么增加运气(透视)真是真的有辅助辅助器(有挂头条)-哔哩哔哩1、we...