Angular Material: Как закрыть все матовые диалоги и сладкие оповещения при выходе из системы

Я хотел закрыть все мои диалоги (mat-dialog, модальные окна начальной загрузки и приятные оповещения) при выходе из системы в Angular. Вот как это было сделано в 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
  }
}

person hakuna    schedule 06.04.2018    source источник


Ответы (2)


Вот что я сделал, чтобы закрыть любой открытый 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, здесь нет способа закрыть или скрыть все открытые диалоговые окна уведомлений. Это то, что я могу сделать до сих пор.

person hakuna    schedule 10.04.2018
comment
Вы правы, но ваше имя переменной вводит в заблуждение. MatDialog — это сама диалоговая служба. Когда вы открываете диалоговое окно, вы получаете dialogRef. :) - person Totati; 05.02.2020

Для тех, кто ищет ответ, если метод .closeAll() недоступен для DialogRef (например, при использовании более новых компонентов @angular/material):

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

constructor(matDialog: MatDialog) {…}

logout() {
    this.matDialog.closeAll();
}
person finki    schedule 12.03.2021
comment
..и если вы хотите что-то сделать после того, как весь диалог закрыт, вы должны использовать this.matDialog.afterAllClosed.pipe(take(1)).subscribe(() => doSomething()) - person Cichy; 01.06.2021