首页 > 解决方案 > Angular Material 的 MatDialog 对话框未关闭

问题描述

我正在使用 Angular 材料对话框的 Angular 6 应用程序。数据成功发送到服务器后,我试图关闭成功对话框。我用了

this.dialogRef.close(0);

或者

this.dialogRef.close(0); 

或者

this.dialogRef.close(); 

但它仍然无法正常工作。

组件1.ts

let NewRegDialog = this.dialog.open(NewRegistrationComponent, {

  width: '750px',
  height: '500px',
  //disableClose: true,
  data: {
    email : email,
    regType : regType,
  },
});

NewRegDialog.afterClosed().subscribe(result => {

  if(result == 1){
    this.dialogRef.close('signup');
  }else{
    alert('Login failed') ;
    });

组件2.ts

    import { Component, OnInit , Inject } from '@angular/core';
    import {  MatDialog  , MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';

    
   ... .. 
   .. .. 
    
      constructor( private restapi: ServicesService , private dialog: MatDialog ,   public dialogRef: MatDialogRef<NewRegistrationComponent>,
        @Inject(MAT_DIALOG_DATA) public data: any ) {
    
   ...
   ..... 
   }
    
    
     user_signup(data) {
    
    
          let userData = {Email: this.email };
          this.restapi.signupUsingSocial(userData).then(
            result => {
              this.responseData = result;
    
              if (this.responseData.status == 1) {
                localStorage.setItem('token', this.responseData.data);
                this.dialogRef.close(1);
    
              } else {
                alert('give proper input');
              }
            },
            err => {
              this.dialogRef.close(0);
            }
          );}}
    

标签: angularangular-material

解决方案


你有这个错误是因为你在 NgZone 之外打开了对话框。

一个简单的解决方法是在构造函数中导入 NgZone:

constructor(public dialogRef: MatDialogRef<ModalComponent>, private ngZone: NgZone) { }

然后在 NgZone 中运行代码

onNoClick(): void {
  this.ngZone.run(() => {
    this.dialogRef.close();
  });
}

这篇文章解释了什么是 NgZone:https ://blog.thoughtram.io/angular/2016/02/01/zones-in-angular-2.html


推荐阅读