Angular 6和材质可以在对话框中显示的不是整个组件,而是仅一部分吗?

时间:2018-11-06 22:15:26

标签: angular angular-material

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

1 个答案:

答案 0 :(得分:1)

如果我正确理解了该问题,则有可能。在组件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
      }
    });

  }