How to pass data to dialog of angular material 2
UPDATE 2 (Angular 5+)
This answer is rather outdated. Take a look at epiphanatic's answer instead.
UPDATE
You can use dialogRef.componentInstance.myProperty = 'some data'
to set the data on your component.
You would need something like this:
let dialogRef = this.dialog.open(DialogComponent, {
disableClose: true,
});
dialogRef.componentInstance.name = 'Sunil';
Then in your DialogComponent
you need to add your name property
:
...
@Component({
...
})
export class DialogComponent {
public name: string;
...
}
Text below is not valid in newer versions of @angular/material
I didn't find any documentation on this, so i started looking into the source code too. Because of that, this might not be the official way of to do.
I successfully located the data in dialogRef._containerInstance.dialogConfig.data
;
So what you can do is for example
let name = dialogRef._containerInstance.dialogConfig.data.name;
console.log(name); // Sunil
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';