How to pass data to dialog of angular material 2

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';

Leave a Comment