首页 文章

如何将数据传递给角材料对话框2

提问于
浏览
17

我正在使用dialog box角度材料2 .

我想将数据传递给打开的组件 . 这是我点击按钮时打开对话框的方式

let dialogRef = this.dialog.open(DialogComponent, {
            disableClose: true,
            data :{'name':'Sunil'}
        });

在文档页面上有data属性,但是我在已安装的软件包中检查了MdDialogConfig

/**
 * 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;
}

配置类中没有数据属性 .

现在我如何访问传递的数据?

2 回答

  • 11

    更新2(Angular 5)

    这个答案已经过时了 . 看看epiphanatic's answer instead .

    更新您可以使用dialogRef.componentInstance.myProperty ='some data'来设置组件上的数据 . 你需要这样的东西:let dialogRef = this.dialog.open(DialogComponent,{
    disableClose:true,
    });
    dialogRef.componentInstance.name ='Sunil';
    然后在您的DialogComponent中,您需要添加您的名称属性:...

    @零件(
    export class DialogComponent {
    公共名称:string;

    ...

    }

    以下文本在较新版本的@ angular / material中无效

    我没有找到任何关于此的文档,所以我也开始研究源代码 . 因此,这可能不是官方的做法 .
    我成功地在dialogRef._containerInstance.dialogConfig.data中找到了数据;所以你可以做的是例如让name = dialogRef._containerInstance.dialogConfig.data.name;
    的console.log(名称); //苏尼尔

  • 30

    对于最新版本的对话框( This is prior to Angular 5, for 5 see update below) ,您可以执行以下操作以通过配置传递数据,这更简单,更清晰 .

    打开对话框时,您可以通过添加数据作为配置参数来实现这一目的(只需忽略宽度和高度,以用于说明目的):

    this.dialogRef = this.dialog.open(someComponent, {
      width: 330px,
      height: 400px,
      data: {
        dataKey: yourData
      }
    });
    

    然后在对话框中打开的组件中,您可以像访问它一样访问它:

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

    或者你可以使用模板或其他方法访问它,但你明白了 .

    UPDATE for Angular 5

    材料中的所有内容都已从Md更改为Mat,因此如果在Angular 5上,导入如下:

    import {MAT_DIALOG_DATA} from '@angular/material'
    

    然后注入像

    @Inject(MAT_DIALOG_DATA) public data: any
    

相关问题