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

新手上路,请多包涵

我正在使用 angular material2 的 对话框

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

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

在文档页面上有数据属性,但我在安装的包中检查了 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;
}

配置类中没有数据属性。

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

原文由 Sunil Garg 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 530
2 个回答

更新 2(角度 5+)

这个答案已经过时了。请看一下 顿悟的答案

更新

您可以使用 dialogRef.componentInstance.myProperty = 'some data' 设置组件上的数据。

你需要这样的东西:

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

然后在你的 DialogComponent 你需要添加你的 name property

 ...

@Component({
  ...
})
export class DialogComponent {
   public name: string;

   ...

}

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

我没有找到任何文档,所以我也开始研究源代码。因此,这可能不是官方的做法。

我成功定位到 dialogRef._containerInstance.dialogConfig.data 中的数据;

所以你可以做的是例如

let name = dialogRef._containerInstance.dialogConfig.data.name;
console.log(name); // Sunil

原文由 Fredrik Lundin 发布,翻译遵循 CC BY-SA 3.0 许可协议

对于 Angular 13,要将对象传递到对话框数据结构中,我必须使用以下内容:

 const dialogRef = this.dialog.open(MyDialog, {
  data: { myObjectHolder: myObject }
});

然后在对话框类中使用:

 private myObject: MyObjectClass;

constructor(@Inject(MAT_DIALOG_DATA) data: { myObjectHolder: MyObjectClass }) {
    this.myObject = data.myObjectHolder;
}

原文由 jllangston 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进