如何将服务变量传递到Angular Material对话框中? [英] How can I pass a service variable into an Angular Material dialog?

查看:81
本文介绍了如何将服务变量传递到Angular Material对话框中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于 mdDialog ,我该怎么办传递变量?具体来说,如何将Angular服务注入对话框组件?

解决方案

要传递变量,可以从MdDialog.open()方法调用返回的MdDialogRef实例中获取在对话框中打开的组件的实例.

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

来自 github material2文档

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

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

解决方案

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

这篇关于如何将服务变量传递到Angular Material对话框中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆