首页 > 解决方案 > 如何打开 MatDialog 并传递 MatDialogRef

问题描述

我正在开发一个角度应用程序。我尝试使用 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);
  });
}

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

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"

你可以帮帮我吗 ?

标签: angularangular-material

解决方案


你让我步入正轨

有这个代码

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

现在它工作正常


推荐阅读