How to Pass Data to a MatDialog in Angular?

A mat dialog is generally used to show a failure or success message to the user when he submits the form. But you might sometimes need to show some more information to the user through the mat dialog.

For example, showing his name, age, address, etc. on submission which changes for every user. Or, in simple words, you have to show some dynamic information.

In such cases, we pass the data from the calling component to the mat dialog which is generally dynamic in nature.

This extra information we can pass from the component to the mat dialog as a second parameter to the open() function. This extra information can be passed as a data key to the mat dialog.

In the below example, we have passed a user’s information as a data key to the mat dialog:

const dialogRef = this.dialog.open(UserDetailsComponent, {
      height: '70%',
      width: '60%',
      data: {
        name: 'John Doe',
        age: 23,
        email: 'johndoe@gmail.com'
      }
});

Now, to access this data in the mat dialog, you have to inject the MAT_DIALOG_DATA in its constructor.

The data variable keeps all the information that has been passed from the component to the mat dialog.

import { Component, Inject, OnInit } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';


constructor(@Inject(MAT_DIALOG_DATA) public data: any) { }

ngOnInit(): void {
    // The 'data' keeps the information sent from the calling component
    console.log(this.data);
}

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.

    View all posts