Angular Material viewchild dialog without dialog component class

Issue

Is there way that I can open an angular material 2 dialog with view child reference without creating a dialog component?

Solution

Try this

View.html

 <button (click)="openModal(mytemplate)">Open my template</button>

 <ng-template #mytemplate>
      <h1>It works</h1>
 </ng-template>

component.ts

 import { MatDialog } from '@angular/material/dialog';

 export class Component implements OnInit {
      constructor(
           public dialog: MatDialog
      ) { }

      openModal(templateRef) {
           let dialogRef = this.dialog.open(templateRef, {
                width: '250px',
                // data: { name: this.name, animal: this.animal }
           });
    
           dialogRef.afterClosed().subscribe(result => {
               console.log('The dialog was closed');
               // this.animal = result;
           });
     }
}

Answered By – Diluk Angelo

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.