Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MatDialog dialog from Angular Material is not closing

I am working on Angular 6 Application where I am using Angular material dialog box. I am trying to close the dialog box on success after the data is sent successfully to the server. I used

this.dialogRef.close(0);

or

this.dialogRef.close(0); 

or

this.dialogRef.close(); 

but it is still not working.

component1.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') ;
    });

component2.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);
            }
          );}}
    
like image 967
Testing Anurag Avatar asked Mar 13 '19 16:03

Testing Anurag


People also ask

How do I close the dialog box in angular 10?

Close Dialog when click outside of its region in Angular Dialog component. By default, dialog can be closed by pressing Esc key and clicking the close icon on the right of dialog header.


2 Answers

You have this error because you open the dialog outside the NgZone.

An easy fix is to import the NgZone in the constuctor:

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

and then run the code in the NgZone

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

this article explains what is an NgZone: https://blog.thoughtram.io/angular/2016/02/01/zones-in-angular-2.html

like image 121
Nico Avatar answered Oct 18 '22 19:10

Nico


For me, the solution was to ensure I was importing BrowserAnimationsModule in my NgModule.

like image 32
Josh Avatar answered Oct 18 '22 19:10

Josh