Angular2 material dialog self close

AngularAngular Material2

Angular Problem Overview


I used angular2 material MdDialog to show a form.

When user submits the form, a request is sent to the backend and if the request is successful, I need to close the dialog. If backend request failed, I need to keep the dialog open.

I can close the dialog by using a button like below.

<button md-raised-button md-dialog-close>Cancel</button>

But, in this case, I only need to close the dialog only if the backend request is successful, so I need a way to programmatically close the dialog.

The component which is shown inside the dialog doesn't have the dialog ref, and I don't know any other way to self close the dialog from the component.

Is there any way I an close the dialog from within the component inside the dialog?

Angular Solutions


Solution 1 - Angular

If you wanna close it from the dialog:

constructor(private dialogRef: MatDialogRef<MyDialogComponent>){ }

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

If you wanna close it from the parent of the dialog:

constructor(private matDialog: MatDialog){}

//anywhere
let dialogRef = this.matDialog.open(MyDialogComponent);
dialogRef.close();

Solution 2 - Angular

As stated in the accepted answer

this.dialogRef.close();

closes the dialog. But most of the time we want the response from server to be rendered immediately without refreshing the page. To do that, we pass the response as an arugument to the close method as shown below

this.dialogRef.close(response);

If you do this, you don't need to do the event emmiter approach found in the docs which is

<button mat-button [mat-dialog-close]="response" cdkFocusInitial>Add</button>

since it closes the dialog before the asynchronous operation finishes.

Solution 3 - Angular

This following works fine for me

this.matDialog.closeAll();

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLahiru ChandimaView Question on Stackoverflow
Solution 1 - AngularPloppyView Answer on Stackoverflow
Solution 2 - AngularDejazmachView Answer on Stackoverflow
Solution 3 - Angularibou layeView Answer on Stackoverflow