在Angular Material中,没有直接提供对dialogRef的提供者。但是我们可以通过创建一个Service来解决这个问题。
首先,创建一个名为DialogService
的新服务:
import { Injectable } from '@angular/core';
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
@Injectable({
providedIn: 'root'
})
export class DialogService {
private dialogRef: MatDialogRef;
constructor(private dialog: MatDialog) { }
openDialog() {
this.dialogRef = this.dialog.open(YourDialogComponent);
}
closeDialog() {
this.dialogRef.close();
}
}
在以上代码中,我们创建了一个dialogRef
变量来存储对话框的引用。然后,我们在openDialog
方法中调用dialog.open()
来打开一个对话框,并将其分配给dialogRef
。最后,我们在closeDialog
方法中调用dialogRef.close()
来关闭对话框。
接下来,将YourDialogComponent
替换为你自己的对话框组件。确保你已经在app.module.ts
中正确导入和声明了对话框组件。
现在,你可以在其他组件中注入DialogService
并使用它来打开和关闭对话框。例如:
import { Component } from '@angular/core';
import { DialogService } from './dialog.service';
@Component({
selector: 'app-your-component',
template: `
`,
})
export class YourComponent {
constructor(private dialogService: DialogService) { }
openDialog() {
this.dialogService.openDialog();
}
closeDialog() {
this.dialogService.closeDialog();
}
}
在以上代码中,我们注入了DialogService
,并使用它的openDialog
和closeDialog
方法来打开和关闭对话框。
希望这可以帮助你解决问题!