首页 > 解决方案 > Angular 6 和 Material 能否在对话框中不显示整个组件,而只显示其中的一部分?

问题描述

我有一个组件和一个表格视图。同一个组件有一个用于添加新记录的表单。我想在对话框中显示此表单,但不要将其放在单独的组件中。这是可能的?

标签: angularangular-material

解决方案


如果我正确理解了这个问题,这是可能的。在您的组件 HTML 中使用 ng-template,其中包含您要在对话框中显示的内容。

<ng-template #dialogTemplate>
    <h1 mat-dialog-title>Title</h1>
    <mat-dialog-content>
      Formgroup for adding item goes here
    </mat-dialog-content>
    <mat-dialog-actions>
      <button mat-button [matDialogClose]='true' mat-icon-button><mat-icon>check</mat-icon></button>
      <button mat-button [matDialogClose]='false' mat-icon-button><mat-icon>cancel</mat-icon></button>
    </mat-dialog-actions>
</ng-template>

然后,在您的 ts 文件中创建一个 ViewChild

  @ViewChild('dialogTemplate') dialogTemplate: TemplateRef<any>;
  constructor(private dialog: MatDialog) { }

然后,您通过从按钮等调用函数来打开对话框。

  open() {
    const dialogRef = this.dialog.open(this.dialogTemplate);

    dialogRef.afterClosed().subscribe(answer => {
      if (answer === true) {
         // logic to save your item goes here
      }
    });

  }

推荐阅读