The other answers already answers the question. But let me provide a more verbose explanation of the solution I used in my use-case.
My requirement was to create a confirm Delete button in dialog. So I want to receive the result whether user confirmed to delete or not.
So my reusable Dialog component
look like below:
import { Component, Inject } from "@angular/core";
import { MatDialogRef, MAT_DIALOG_DATA } from "@angular/material/dialog";
import { ConfirmDialogDAO } from "./confirm.dialog.dao";
@Component({
templateUrl: "./confirm.dialog.html"
})
export class ConfirmDialog {
constructor(@Inject(MAT_DIALOG_DATA) public data: ConfirmDialogDAO,
private dialogRef: MatDialogRef<ConfirmDialog>) {
}
yesButtonClicked(): void {
this.dialogRef.close(true);
}
}
The above dialogRef is important because using that you can emit events based on user action on that component while dialog gets closed.
In my case, I only wanted to emit event when user clicked on confirm delete button. So the below is my html in dialog component:
<h1 mat-dialog-title>{{ data.title }}</h1>
<div mat-dialog-content>
{{ data.description }}
</div>
<div mat-dialog-actions>
<button mat-raised-button mat-dialog-close color="warn" (click)="yesButtonClicked()">{{ data.yesButtonName }}</button>
<button mat-raised-button mat-dialog-close color="accent" cdkFocusInitial>{{ data.noButtonName }}</button>
</div>
If you notice, only when user clicks on +ve confirmation button, then I am emitting an event.
Now in the actual component where I wanted to reuse this dialog, this is how I invoked the dialog and performed action on data return:
import { MatDialog } from '@angular/material/dialog';
@Component({
templateUrl: './another.component.html',
styleUrls: ['./another.component.css']
})
export class AnotherComponent {
constructor(private dialog: MatDialog) { }
deleteInputNode(): void {
this.dialog.open(ConfirmDialog, {
data: {
title: `Delete input node?`,
description: `Please confirm:`,
yesButtonName: `Delete`,
noButtonName: `Cancel`
},
}).afterClosed().subscribe(data => {
if (data) {
alert("Delete"); // Perform one action
} else {
alert("Not delete"); // Perform another action
}
});
}
}
So subscribing to afterClosed() event will give us access to data returned from dialog component.
In my case, I only returned true / false value, but you can also emit objects: {key: value}
. So in that case you can access that data in afterClosed() subscription using data.key.
Resource: Refer to this live example from stackblitz in case my explanation lacks some details: https://stackblitz.com/edit/matdialog-return-data-demo-qqscz9?file=app%2Ffile-name-dialog.component.ts