您好!以下是一个示例代码,展示了如何使用Angular Material对话框并立即关闭它:
ng add @angular/material
import { MatDialog, MatDialogRef } from '@angular/material/dialog';
constructor(private dialog: MatDialog) { }
openDialog(): void {
const dialogRef: MatDialogRef = this.dialog.open(DialogComponent, {
width: '250px',
data: { name: 'John' }
});
dialogRef.afterClosed().subscribe(result => {
console.log('The dialog was closed');
});
}
import { Component, Inject } from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material/dialog';
@Component({
selector: 'app-dialog',
templateUrl: 'dialog.component.html',
})
export class DialogComponent {
constructor(
public dialogRef: MatDialogRef,
@Inject(MAT_DIALOG_DATA) public data: any) { }
onCancelClick(): void {
this.dialogRef.close();
}
}
这样,当您调用openDialog方法时,对话框将会打开,并且在关闭后会在控制台上输出一条消息。