“没有 MdDialogRef 的提供者!"; [英] "No provider for MdDialogRef!"

查看:40
本文介绍了“没有 MdDialogRef 的提供者!";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个组件:

@Component({
  selector: 'pizza-dialog',
  template: `
  <h1 md-dialog-title>Would you like to order pizza?</h1>

  <md-dialog-actions>
    <button (click)="dialogRef.close('yes')">Yes</button>
    <button md-dialog-close>No</button>
  </md-dialog-actions>
  `
})
export class PizzaDialog {
  constructor(public dialogRef: MdDialogRef<PizzaDialog>) { }
}

我已经将 MdDialog 导入我的应用模块:

I've already imported MdDialog into my app module:

@NgModule({
  imports: [
    BrowserModule,
    MaterialModule.forRoot(),
    MdDialogModule.forRoot(),
  ],
  ...
})

为什么会出现这个错误?

Why would I get this error?

没有 MdDialogRef 的提供者!

No provider for MdDialogRef!

推荐答案

您可能已经尝试在这样的模板中使用对话框组件:

You may have tried to use your dialog component in a template like this:

<pizza-dialog ...></pizza-dialog>

从模板中删除它并使用 MdDialog.open() 打开对话框,如下所示:

Delete that from your template and open the dialog using MdDialog.open() as is done here:

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

  dialogRef: MdDialogRef<PizzaDialog>;

  constructor(public dialog: MdDialog) { }

  openDialog() {
    this.dialogRef = this.dialog.open(PizzaDialog, {
      disableClose: false
    });

    this.dialogRef.afterClosed().subscribe(result => {
      console.log('result: ' + result);
      this.dialogRef = null;
    });
  }
}

此代码复制自:https://github.com/angular/material2/blob/master/src/lib/dialog/README.md

这篇关于“没有 MdDialogRef 的提供者!";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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