Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular material: is it possible to create modals (or dialogs) with ng-template?

In my project I am using ngx-bootstrap's dialog component which takes your ng-template and displays it as your modal.

Using ng-template is advantageous for many reasons and most importantly, there is no communication barrier (between modal and origin component) if ng-template live in same component. This way I can call my component method without any problems. For example, in following code selectNextRow() will change row in my table and hence selectedRow_Session and thus data of next row will be displayed on modal.

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>

In Angular Material Dialogs, I could only find API to that can create modals with only Component and not with ng-template.

Is there a way to do this, with or without dialogs, using Angular Material?

like image 543
asdasd Avatar asked Jan 01 '23 14:01

asdasd


1 Answers

As mentioned in comments, you can use a TemplateRef with @angular/material MatDialog. You can find the API reference here : Angular Material MatDialog.

Here is a minimal example showing how to do it :

    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');
         });
       }
     }

And here is a live example using Angular v6 : Stackblitz Live Example.

Hope it helps!

like image 158
GeoAstronaute Avatar answered Jan 13 '23 11:01

GeoAstronaute