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); }