How can I pass a service variable into an Angular Material dialog?

ethan picture ethan · Nov 17, 2016 · Viewed 42.2k times · Source

For mdDialog, how do I pass in variable? Specifically, how to inject an Angular service into the dialog component?

Answer

poidar picture poidar · Dec 7, 2016

For passing variables you can grab the instance of the component opened in the dialog, from the MdDialogRef instance returned in the MdDialog.open() method call.

dialogRef = this.dialog.open(PizzaDialog, config)
dialogRef.componentInstance.<property_name>

Modified Pizza from the github material2 docs

@Component({
  selector: 'pizza-component',
  template: `
  <button type="button" (click)="openDialog()">Open dialog</button>
  `
})
export class PizzaComponent {

  constructor(public dialog: MdDialog) { }

  openDialog() {
    let config = new MdDialogConfig();
    let dialogRef:MdDialogRef<PizzaDialog> = this.dialog.open(PizzaDialog, config);
    dialogRef.componentInstance.name = "Ham and Pineapple";
    dialogRef.componentInstance.size = "Large";
  }
}

@Component({
  selector: 'pizza-dialog',
  template: `
  <h2>{{name}}</h2>
  <p>Size: {{size}}</p>
  <button type="button" (click)="dialogRef.close('yes')">Yes</button>
  <button type="button" (click)="dialogRef.close('no')">No</button>
  `
})
export class PizzaDialog {
  name:string;
  size:string;
  constructor(public dialogRef: MdDialogRef<PizzaDialog>) { }
}