我想为那些还在学习的人提供更详细的答案:
与我配置 Material 示例不同,我将对话框配置为具有自己的组件文件(html、css 和 ts)以便于调试。
主组件文件 "x.component.ts" (调用对话框)
1)添加导入语句
import { MatDialog} from '@angular/material';
2) 将该属性添加到构造函数参数中。
public dialog: MatDialog
3) 定义调用对话框的代码
openDialog(title: string, text: string): void {
const dialogRef = this.dialog.open(DialogComponent, {
width: '350px',
data: {dialogTitle: title, dialogText: text}
);
dialogRef.afterClosed().subscribe(result => {
});
const dialogSubmitSubscription =
dialogRef.componentInstance.submitClicked.subscribe(result => {
dialogSubmitSubscription.unsubscribe();
});
在您的HTML文件中使用openDialog()函数调用该函数。我正在引用DialogComponent,请确保它已经导入到您的模块中。
import { DialogComponent } from './dialog/dialog.component';
同样也
entryComponents: [DialogComponent]
在entryComponents数组中声明它
4)在dialog.component.ts文件中添加导入
import { Component, Output, EventEmitter, Inject, OnInit} from '@angular/core';
import { MatDialogRef, MAT_DIALOG_DATA } from '@angular/material';
5) 定义属性和函数
dialogTitle: string;
dialogText: string;
@Output() submitClicked = new EventEmitter<any>();
constructor(
public dialogRef: MatDialogRef<DialogComponent>,
@Inject(MAT_DIALOG_DATA) public data: DialogData) {}
ngOnInit() {
this.dialogTitle = this.data.dialogTitle;
this.dialogText = this.data.dialogText;
}
saveMessage() {
const data = 'Your data';
this.submitClicked.emit(data);
this.dialogRef.close();
}
closeDialog() {
this.dialogRef.close();
}
最后是HTML
<h1 mat-dialog-title>{{dialogTitle}}"</h1>
<div mat-dialog-content>
<p>{{dialogText}}</p>
</div>
<div mat-dialog-actions>
<button mat-button (click)="saveMessage()" >Ok</button>
<button mat-button (click)="closeDialog()" cdkFocusInitial>No Thanks</button>
</div>
希望它有所帮助。