【问题标题】:Angular material: is it possible to create modals (or dialogs) with ng-template?Angular 材料:是否可以使用 ng-template 创建模态(或对话框)?
【发布时间】:2018-11-25 13:32:41
【问题描述】:

在我的项目中,我使用了ngx-bootstrap's 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 来做到这一点,不管有没有对话框?

【问题讨论】:

  • API 文档显示 open() 接受 TemplateRef。所以是的,这是可能的。
  • @JBNizet 你是对的!非常感谢!

标签: angular angular-material


【解决方案1】:

如 cmets 中所述,您可以将 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

希望对你有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多