I am using dialog box of angular material2.
I want to pass data to the opened component. Here is how I am opening dialog box on click of a button
let dialogRef = this.dialog.open(DialogComponent, { disableClose: true, data :{'name':'Sunil'} });
On the documentation page there is data property, But I checked MdDialogConfig in my installed packages
/** * Configuration for opening a modal dialog with the MdDialog service. */ export declare class MdDialogConfig { viewContainerRef?: ViewContainerRef; /** The ARIA role of the dialog element. */ role?: DialogRole; /** Whether the user can use escape or clicking outside to close a modal. */ disableClose?: boolean; /** Width of the dialog. */ width?: string; /** Height of the dialog. */ height?: string; /** Position overrides. */ position?: DialogPosition; }
there is no data property in configuration class.
Now How can I access that passed data?
In the class file, import the MatDialog class from @angular/material package to provide the open() method. This method takes the component we want to open as a first argument. In the second argument we pass option object which is also having the data property using which we can pass data to the Modal.
You can pass any kind of data to the component by adding data to the MatDialog's open() options. }, }); You can retrieve the data by injecting MAT_DIALOG_DATA in the opened component.
MatDialog creates modal dialogs that implements the ARIA role="dialog" pattern by default. You can change the dialog's role to alertdialog via MatDialogConfig . You should provide an accessible label to this root dialog element by setting the ariaLabel or ariaLabelledBy properties of MatDialogConfig .
For the newest version of dialog (This is prior to Angular 5, for 5 see update below), you can do the following to pass data via the config which is much simpler and cleaner.
When you open the dialog, you can do it this way by adding data as a config param (just ignore the width and height which is there for illustration purposes):
this.dialogRef = this.dialog.open(someComponent, { width: '330px', height: '400px', data: { dataKey: yourData } });
Then in the component that is opened in the dialog, you can access it like:
import {MD_DIALOG_DATA} from '@angular/material'; import { Inject } from '@angular/core'; constructor( @Inject(MD_DIALOG_DATA) public data: any ) { } ngOnInit() { // will log the entire data object console.log(this.data) }
Or you can use access it in the template or other methods, but you get the point.
UPDATE for Angular 5
Everything in the material has been changed from Md to Mat, so if on Angular 5, import like:
import {MAT_DIALOG_DATA} from '@angular/material'
Then inject like
@Inject(MAT_DIALOG_DATA) public data: any
UPDATE for Angular 9
MAT_DIALOG_DATA import location has changed to:
import {MAT_DIALOG_DATA} from '@angular/material/dialog';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With