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

时间:2018-04-06 13:38:19

标签: angular angular-material ng-bootstrap sweetalert2

我希望在Angular的注销时关闭所有对话框(mat-dialog,bootstrap modals& sweet alert)。这是在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
  }
}

2 个答案:

答案 0 :(得分:15)

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

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

export class myClass {

constructor(private dialogRef: MatDialog) {
}

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

}

如果您只想关闭特定对话框,可以循询dialogRef.openDialogs并使用close()

关闭相应的对话框

这是关闭任何打开/活动甜蜜警报对话框的方法:

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不同,没有可用于关闭或隐藏所有打开的甜蜜警报对话框的方法。这是我迄今为止能够做到的。

答案 1 :(得分:5)

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

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

constructor(matDialog: MatDialog) {…}

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