15

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

Shansana Waruna
  • 379
  • 1
  • 3
  • 12
  • can you elaborate the question – Aravind Jan 19 '18 at 06:44
  • like in ngx-bootstrap modal, Is there a way to open angular material 2 dialog with template reference in html. like this without creating component class for the dialog. use dialog just in html template of another component , https://valor-software.com/ngx-bootstrap/#/modals#service-template – Shansana Waruna Jan 19 '18 at 06:48
  • you can use which one is comfortable for you and supports your need. But to make the modal a reusable one I will suggest you to go with the child component – Aravind Jan 19 '18 at 06:55
  • Thanks for the help. Can you provide me a simple example to load dialog without using component class and inside a component view? like in the ngx-bootstrap template modal? – Shansana Waruna Jan 19 '18 at 06:58
  • Refer this [**answer**](https://stackoverflow.com/questions/42735858/how-to-implement-modal-dialog-in-angular-2-and-above/42736058#42736058) – Aravind Jan 19 '18 at 06:59
  • I am using Angular Material 2. Not ngx-bootstrap – Shansana Waruna Jan 19 '18 at 07:53

1 Answers1

27

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;
           });
     }
}
Madhu Jayarama
  • 415
  • 1
  • 5
  • 15
Diluk Angelo
  • 1,503
  • 11
  • 21