如何打开MatDialog并传递MatDialogRef

时间:2019-11-09 12:03:09

标签: angular angular-material

我正在开发一个有角度的应用程序。我尝试使用MatDialog打开一个对话框,然后尝试将其关闭

我以此方式打开对话框

openDialog(event) {
  const dialogConfig = new MatDialogConfig();
  dialogConfig.disableClose = true;
  dialogConfig.autoFocus = true;
  dialogConfig.position = {
    top:  bottom + 'px',
    right: '0px'
  };
  dialogConfig.width = '50%';
  dialogConfig.height = '590px';

  this.dialog.open(UserDialogComponent, dialogConfig);

  const dialogRef = this.dialog.open(UserDialogComponent, dialogConfig);

  dialogRef.beforeClose().subscribe((result: string) => {
    console.log('RIght before close,', result);
  });
  dialogRef.afterClosed().subscribe(result => {
    console.log('The dialog was closed', result);
  });
}

我将MatDialogRef注入UserDialogComponent的构造函数中:

constructor(
    private formBuilder: FormBuilder,
    private dialogRef: MatDialogRef<UserDialogComponent>,
    @Inject(MAT_DIALOG_DATA) data) {
      console.log("Constructor UserDialogComponent START");
      console.log(dialogRef);
      this.dialogRef = dialogRef;
      console.log("Constructor UserDialogComponent END");
     }

然后使用此功能关闭对话框

  close() {
    console.log(this.dialogRef);
    console.log('CLOSE CLICKED');
    this.dialogRef.close(true);
  }

但是this.dialogRef是一个空对象,当我调用此函数时收到以下错误

ERROR TypeError: "this.dialogRef.close is not a function"

你能帮我吗?

2 个答案:

答案 0 :(得分:1)

你让我步入正轨

有此代码

@Component({
  selector: 'app-user-dialog',
  templateUrl: './user-dialog.component.html',
  styleUrls: ['./user-dialog.component.scss'],
  providers: [
    {provide: MAT_RADIO_DEFAULT_OPTIONS, useValue: { color: 'accent' }},
    { provide: MatDialogRef, useValue: {} }
  ]
})
export class UserDialogComponent implements OnInit {

我删除了

{ provide: MatDialogRef, useValue: {} }

现在工作正常

答案 1 :(得分:0)

删除此this.dialogRef = dialogRef;并尝试

 @Inject(MAT_DIALOG_DATA) data) {
      console.log("Constructor UserDialogComponent START");
      console.log(dialogRef);
      this.dialogRef = dialogRef; // delete this line
      console.log("Constructor UserDialogComponent END");
     }