MdDialogRef.close doesn't close the dialog when called from a callback fn

573 views Asked by At

I followed official https://material.angular.io/components/dialog/overview where it states that if the dialog component itself has to be closed, we need to inject MdDialogRef reference as below and then close on an event

export class LoginDialogComponent {
  constructor(public dialogRef: MdDialogRef<LoginDialogComponent>,
      @Inject(MD_DIALOG_DATA) public data: any, public afAuth: AngularFireAuth, private router: Router) {
  }

  closeDialog(): void {
    this.dialogRef.close();
  }

  signInWithGoogle() {
    const self = this;
    this.afAuth.auth
        .signInWithPopup(new firebase.auth.GoogleAuthProvider())
        .then(res => {
          self.closeDialog();
        });
  }
}

On successful response from Google OAuth, I see that closeDialog() is called. However, the dialog isn't closed. [I have no issues closing dialog as part of setTimeOut/UserAction]

2

There are 2 answers

0
Shadoweb On

I found a hack for this to work. It seems that once returned from the callback there are no possible interaction with the dialogRef, however it still can be interacted with from outside. And it will trigger the close if you call dialogRef.getState().

const dialogRef = this.dialog.open(MyModalComponent, {
  width: '362px'
});

// dirty, but functional hack
const closeCheck = setInterval(() => {
  if (dialogRef.getState() === 2) {
    clearInterval(closeCheck);
  }
}, 200);
1
Eric Jeker On

Not sure it's related but had the same problem and I tracked it down to the fact that I had a form in my dialog and I was using ngModel for dual binding in my inputs but the object I was binding to was undefined.

Below, if that input is in the dialog, if data.media.i18n.en.title is undefined, there will be no exception in the console and the mdDialog will not close.

<input id="title" name="title" [(ngModel)]="data.media.i18n.en.title">

So before opening my dialog I had to initialize that object correctly:

// before opening the dialog, initialize the variable
if (typeof media.i18n === 'undefined') {
  media.i18n = {
    fr: {
      title: ''
    }
  };
}

let dialogRef = this.dialog.open(EditMediaDialogComponent, {
  data: {
    media: media
  }
});

You can test that here: https://plnkr.co/edit/95atm4PIeKvyorVkcD0f?p=preview

That plnkr fails. If you want to correct it, define animal.name before opening the dialog.

Also, when it fails, you can see that there is no animation on the dialog.

Not sure it's your case as you didn't publish much code.