How to Pass Data from a Mat Dialog to Parent Component in Angular?

When you are working with Angular, it’s quite common to pass the data from a mat dialog to the parent component when the mat dialog closes.

This can be done in two easy steps.

Step 1: Send data from the mat dialog-

To send the data from the mat dialog, you have to first inject the MatDialogRef into the constructor of the dialog component. The MatDialogRef gives you a method close(), which closes the dialog box and sends the data to the parent component:

import { MatDialogRef } from '@angular/material/dialog';

export class DialogComponent implements OnInit {

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

    ngOnInit(): void { }

    closeDialog() {
        let data = {
          userName: 'John Doe',
          email: 'johndoe@gmail.com'
        }
        // Send data to the parent component
        this.dialogRef.close(data); 
    }
}

Step 2: Access data in the Parent component-

To access the data sent from the dialog box, you have to subscribe to the afterClosed() method which returns the data as an observable.

Here is the implementation:

openDialog() {
  // Open the dialog
  const dialogRef = this.dialog.open(DialogComponent, { 
    height: '70%',
    width: '60%',
  });

  // Subscribe when the dialog box closes
  dialogRef.afterClosed().subscribe(
    (res)=>{
      // Receive data from dialog component
      // res contains data sent from the dialog
      console.log(res);
    }
  );
}

Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.