Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

typescript - How to pass data to dialog of angular material 2

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...