在 Angular 10 中,ModalDialogService
不再可用,因为它已被废弃。取而代之的是使用 Angular Material 中的 MatDialog
组件来创建模态对话框。
以下是一个解决方法的代码示例:
@angular/material
包。如果没有安装,可以使用以下命令进行安装:npm install @angular/material
MatDialog
:import { MatDialog } from '@angular/material/dialog';
MatDialog
:constructor(private dialog: MatDialog) { }
openDialog() {
const dialogRef = this.dialog.open(YourDialogComponent, {
width: '250px',
data: { name: 'John', age: 30 } // 传递给模态对话框的数据
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
console.log(result); // 模态对话框关闭时返回的结果
});
}
import { Component, Inject } from '@angular/core';
import { MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'app-your-dialog',
template: `
Modal Dialog
Name: {{ data.name }}
Age: {{ data.age }}
`,
})
export class YourDialogComponent {
constructor(@Inject(MAT_DIALOG_DATA) public data: any) { }
closeDialog() {
// 关闭模态对话框
this.dialogRef.close();
}
}
在上述代码中,YourDialogComponent
是用来显示模态对话框的组件。你可以根据自己的需求进行自定义。
最后,在你的模板文件中添加一个按钮或其他触发器来调用 openDialog()
方法:
当点击按钮时,将会打开一个基于 YourDialogComponent
组件的模态对话框。