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。

相关内容

热门资讯

总结透视!hhpoker辅助器... 总结透视!hhpoker辅助器视频,微乐自建房免费辅助入口在哪里,大纲教程(真的有挂)-哔哩哔哩1、...
了解透视!hhpoker怎么防... 了解透视!hhpoker怎么防作弊,微乐家乡破解版,窍门教程(有挂方法)-哔哩哔哩1、了解透视!hh...
揭幕透视!佛手大菠萝有挂吗,微... 揭幕透视!佛手大菠萝有挂吗,微乐自建房道具有用吗,演示教程(有挂透视)-哔哩哔哩1、佛手大菠萝有挂吗...
详细透视!德普之星私人局辅助免... 详细透视!德普之星私人局辅助免费,微信小程序微乐房间怎么开挂,机巧教程(有挂解惑)-哔哩哔哩1、德普...
解密透视!wpk插件,微信微乐... 解密透视!wpk插件,微信微乐跑得快游戏辅助脚本,资料教程(有挂助手)-哔哩哔哩1、上手简单,内置详...
辅助透视!wepoker透视脚... 辅助透视!wepoker透视脚本免费下载,微信小程序微乐陕西挖坑辅助,手段教程(有挂方法)-哔哩哔哩...
必备透视!约局吧德州真的存在透... 必备透视!约局吧德州真的存在透视吗,微乐游戏小程序辅助器免费,秘籍教程(有挂实锤)-哔哩哔哩该软件可...
必备透视!wepoker私人局... 必备透视!wepoker私人局透视,如何提高微乐自建胜率,演示教程(有挂方法)-哔哩哔哩亲,关键说明...
了解透视!德州局怎么透视,微信... 了解透视!德州局怎么透视,微信小程序微乐挂如何获取,机巧教程(有挂攻略)-哔哩哔哩小薇(辅助器软件下...
解密透视!wepoker免费脚... 解密透视!wepoker免费脚本咨询,手机微乐小程序破解器,经验教程(有挂教学)-哔哩哔哩1、实时w...