首页 > 解决方案 > Angular 材料:是否可以使用 ng-template 创建模态(或对话框)?

问题描述

在我的项目中,我使用了 ngx-bootstrap 的对话框组件,它接受您ng-template并将其显示为您的模式。

ng-template由于许多原因,使用是有利的,最重要的是,如果ng-template存在于同一个组件中,则没有通信障碍(模态组件和原始组件之间)。这样我就可以毫无问题地调用我的组件方法。例如,在下面的代码selectNextRow()中将更改我表中的行,因此selectedRow_Session下一行的数据将显示在模态中。

app.component.ts

/** display selectedRow_Session on modal */
<ng-template #sessionDetailTemplate>

      <app-session-detail-model
        [session]="selectedRow_Session"
        [bot]="bot"
        (selectNextRow)="selectNextRow()"
        (closeModel$)="modalRef.hide()"
        (selectPrevRow)="selectPrevRow()"
        [pageNumberOfCurrentRowSelected]="pageNumberOfCurrentRowSelected"
        [indexOfCurrentRowSelected]="indexOfCurrentRowSelected"
        [finalDfState]="selectedRow_Session.df_state"
        [sessionDataStore]="selectedRow_Session.data_store">
      </app-session-detail-model>

</ng-template>

在 Angular Material Dialogs 中,我只能找到可以使用 onlyComponent而不是创建模态的 API ng-template

有没有办法使用Angular Material来做到这一点,无论有没有对话框?

标签: angularangular-material

解决方案


如评论中所述,您可以将 TemplateRef 与 @angular/material MatDialog 一起使用。您可以在此处找到 API 参考:Angular Material MatDialog

这是一个显示如何执行此操作的最小示例:

    import { Component, ViewChild, TemplateRef } from '@angular/core';
    import { MatDialog } from '@angular/material';

    @Component({
     selector: 'dialog-overview-example',
     template: `
      <div [style.margin.px]="10">
        <button mat-raised-button (click)="openDialog()">Open Modal via Component Controller</button>
      </div>
      <div [style.margin.px]="10">
        <button mat-raised-button (click)="dialog.open(myTemplate)">Open Modal directly in template</button>
      </div>

    <ng-template #myTemplate>
      <div>
        <h1>This is a template</h1>
      </div>
    </ng-template>
    `
    })
    export class DialogOverviewExample {
      @ViewChild('myTemplate') customTemplate: TemplateRef<any>;

      constructor(public dialog: MatDialog) {}

      openDialog(): void {
         const dialogRef = this.dialog.open(this.customTemplate, {
            width: '250px'
         });

         dialogRef.afterClosed().subscribe(() => {
           console.log('The dialog was closed');
         });
       }
     }

这是一个使用 Angular v6 的实时示例:Stackblitz Live Example

希望能帮助到你!


推荐阅读