如何将材质2对话框Angular 2中的数据从1个组件发送到另一个组件

时间:2017-02-03 07:51:15

标签: angular angular-material2

我正在使用Material 2 diloge,我能够获得关于diloge的数据。

但我无法找到任何解决方案来发送关于diloge的数据 使用@input

import {Component} from '@angular/core';
import {MdDialog, MdDialogRef} from '@angular/material';


@Component({
  selector: 'dialog-result-example',
  templateUrl: './dialog-result-example.html',
})
export class DialogResultExample {
  selectedOption: string;

  constructor(public dialog: MdDialog) {}

  openDialog() {
    let dialogRef = this.dialog.open(DialogResultExampleDialog);
    dialogRef.afterClosed().subscribe(result => {
      this.selectedOption = result;
    });
  }
}


@Component({
  selector: 'dialog-result-example-dialog',
  templateUrl: './dialog-result-example-dialog.html',
})
export class DialogResultExampleDialog {
  constructor(public dialogRef: MdDialogRef<DialogResultExampleDialog>) {}
}

2 个答案:

答案 0 :(得分:5)

您可以使用MdDialogRefcomponentInstance属性,yurzuiquestion的答案的第8步中建议。< / p>

例如,如果您想将值 foo 传递给param1中的变量DialogResultExampleDialog,则可以执行以下操作:

import {Component} from '@angular/core';
import {MdDialog, MdDialogRef} from '@angular/material';


@Component({
  selector: 'dialog-result-example',
  templateUrl: './dialog-result-example.html',
})
export class DialogResultExample {
  selectedOption: string;

  constructor(public dialog: MdDialog) {}

  openDialog() {
    let dialogRef = this.dialog.open(DialogResultExampleDialog);
    dialogRef.componentInstance.param1 = "foo";
    dialogRef.afterClosed().subscribe(result => {
      this.selectedOption = result;
    });
  }
}


@Component({
  selector: 'dialog-result-example-dialog',
  templateUrl: './dialog-result-example-dialog.html',
})
  param1: string;

  export class DialogResultExampleDialog {
  constructor(public dialogRef: MdDialogRef<DialogResultExampleDialog>) {}
}

答案 1 :(得分:3)

另一种方法是,您可以使用MdDialogConfig

import {Component} from '@angular/core';
import {MdDialog, MdDialogRef, MdDialogConfig} from '@angular/material';


@Component({
  selector: 'dialog-result-example',
  templateUrl: './dialog-result-example.html',
})
export class DialogResultExample {
  selectedOption: string;

  constructor(public dialog: MdDialog) {}

  openDialog() {
    let config = new MdDialogConfig;
    if (id) {
      config.data = { id: id }
    } else config.data = null;

    let dialogRef = this.dialog.open(DialogResultExampleDialog, config);
    dialogRef.afterClosed().subscribe(result => {
      this.selectedOption = result;
    });
  }
}


@Component({
  selector: 'dialog-result-example-dialog',
  templateUrl: './dialog-result-example-dialog.html',
})
export class DialogResultExampleDialog {
  constructor(public dialogRef: MdDialogRef<DialogResultExampleDialog>) {
    if (dialogRef.config.data) {
            // do something...
     }
  }
}