Angular Material: 如何在注销时关闭所有 mat-dialogs 和 sweet-alerts

Angular Material: How to close all mat-dialogs and sweet-alerts on logout

我想在 Angular 注销时关闭所有对话框(mat-dialog、bootstrap 模态和甜蜜警报)。这是在 AngularJS(1.5 版)中的做法:

function logout() {
  //hide $mdDialog modal
  angular.element('.md-dialog-container').hide();

  //hide any open $mdDialog modals & backdrop
  angular.element('.modal-dialog').hide();
  angular.element('md-backdrop').remove();

  //hide any open bootstrap modals & backdrop
  angular.element('.inmodal').hide();
  angular.element('.fade').remove();

  //hide any sweet alert modals & backdrop
  angular.element('.sweet-alert').hide();
  angular.element('.sweet-overlay').remove();
}

如何在 Angular 中执行此操作?使用 $('.mat-dialog-container')$('.inmodal') 并没有让我选择执行 hide()close()

我尝试这样做,但我无法获取元素引用:

import { ElementRef, Injectable, ViewChild } from '@angular/core';
import { MatDialog, MatDialogContainer, MatDialogRef } from '@angular/material';

export class MyClass
{
  @ViewChild('.mat-dialog-container') _matDialog: ElementRef;
  @ViewChild('.mat-dialog-container') _matDialogRef:MatDialogRef<MatDialog>;

  constructor() { }

  function logout()
  {
    //access the dialogs here
  }
}

这是我在整个应用程序中关闭任何打开的 mat-dialog 所做的:

import {MatDialog} from '@angular/material';

export class myClass {

constructor(private dialogRef: MatDialog) {
}

logOut()
{
  this.dialogRef.closeAll();
}

}

如果您只想关闭一个特定的对话框,您可以遍历 dialogRef.openDialogs 并使用 close()

关闭相应的对话框

这是关闭任何 open/active 甜蜜警报对话框的方法:

const sweetAlertCancel = document.querySelector('.swal2-cancel') as HTMLElement;

if (sweetAlertCancel) {
    sweetAlertCancel.click(); //only if cancel button exists
}

const sweetAlertConfirm = document.querySelector('.swal2-confirm') as HTMLElement;

if (sweetAlertConfirm) {
   sweetAlertConfirm.click(); //if cancel doesn't exist , confirm is the equivalent for Ok button
}

material-dialog 不同,没有可用于关闭或隐藏所有打开的甜蜜警报对话框的方法。这是我目前能做的。

对于任何寻求答案的人,如果方法 .closeAll()DialogRef 上不可用(例如,如果使用较新的 @angular/material 组件):

import {MatDialog} from '@angular/material/dialog';

constructor(matDialog: MatDialog) {…}

logout() {
    this.matDialog.closeAll();
}