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。

相关内容

热门资讯

2026版攻略!wpk控制牌是... 2026版攻略!wpk控制牌是真的吗,智星德州可以透视吗,切实真的有挂(有挂教学)暗藏猫腻,小编详细...
攻略辅助挂!wepoker养号... 攻略辅助挂!wepoker养号规律,德普之星透视免费,真是存在有挂(有挂存在)1、超多福利:超高返利...
有了最新消息!wpk模拟器多开... 有了最新消息!wpk模拟器多开,德普之星怎么设置埋牌,确实是真的有挂(的确有挂)1、德普之星怎么设置...
连日来!拱趴大菠萝万能挂,德普... 连日来!拱趴大菠萝万能挂,德普之星辅助软件,果然真的有挂(有挂分享)1、实时德普之星辅助软件透视辅助...
更值得关注的是!德州局透视脚本... 更值得关注的是!德州局透视脚本免费版下载手机版,如何下载德普之星辅助软件,原来是真的有挂(详细教程)...
昨日!wepoker分析,红龙... 昨日!wepoker分析,红龙poker辅助,真是确实有挂(有挂工具)红龙poker辅助脚本下载中分...
经调查!拱趴游戏破解器,德扑之... 您好,德扑之星辅助器app这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
做出回应!aapoker安装包... 做出回应!aapoker安装包怎么使用,德普之星怎么设置埋牌,其实真的有挂(真实有挂);1、用户打开...
经调查!hh poker插件下... 经调查!hh poker插件下载,德扑之星的辅助工具介绍,其实是真的有挂(存在有挂)1、德扑之星的辅...
日前!菠萝辅助器免费版的特点,... 日前!菠萝辅助器免费版的特点,德普之星有透视辅助吗,一贯是真的有挂(真实有挂)1、玩家可以在德普之星...