Angular 材质:是否可以使用 ng-template 创建模态(或对话框)?

问题描述 投票:0回答:1

在我的项目中,我使用ngx-bootstrap的dialog组件,它接受你的

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 中,我只能找到可以仅使用

Component
而不是使用
ng-template
创建模态的 API。

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

angular angular-material
1个回答
18
投票

正如评论中提到的,您可以将 TemplateRef 与 @angular/material MatDialog 一起使用。您可以在这里找到 API 参考:Angular Material MatDialog

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

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

    @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 实时示例

希望有帮助!

© www.soinside.com 2019 - 2024. All rights reserved.