Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dialog in Angular without Component

Tags:

angular

dialog

Is there a way in Angular 8 to generate a small dialog without having to create a new Component? Some small message like "Operation completed" that wouldn't require much interaction with the user. I just feel like having 4 more files in a project just to display a success message would be too much:

small-dialog.component.html
small-dialog.component.scss
small-dialog.component.spec.ts
small-dialog.component.ts

Or maybe there's a way to create a "default component" in few lines without having to actually generate a new component?

like image 820
Robb1 Avatar asked Feb 21 '20 14:02

Robb1


People also ask

How do you create a dialog box in angular?

First we need to import 'MatDialog' from '@angular/material/dialog' and we need to create an instance for it in the constructor. Using this instance we can open the dialog box component. Now create a separate component for the dialog and write code as per the requirements.

What is MatDialog in angular?

MatDialog creates modal dialogs that implements the ARIA role="dialog" pattern by default. You can change the dialog's role to alertdialog via MatDialogConfig . You should provide an accessible label to this root dialog element by setting the ariaLabel or ariaLabelledBy properties of MatDialogConfig .

How do I get data from MatDialog?

You can pass any kind of data to the component by adding data to the MatDialog's open() options. }, }); You can retrieve the data by injecting MAT_DIALOG_DATA in the opened component.

How do you create a modal dialog component in angular 8?

Here we need to do three things: Inject a MatDialogRef object in the component to have access to the dialog's methods (namely, to close the dialog); Create the actionFunction() function for the “Logout” button; Create the closeModal() function for the “Go back” button.


1 Answers

If you don't want to create component for dialog itself you can do something like this:

View.html

<button (click)="openDialog(template)">Open my dialog</button>
<ng-template #template>
 <h1>This is a message</h1>
</ng-template>

Component.ts

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


constructor(dialog: MatDialog) {}

openDialog(templateRef) {
  let dialogRef = this.dialog.open(templateRef, {
   width: '300px'
 });
}

Here is also one example how you can do the same thing.

But I propose to you that you create generic dialog component which you can use through the whole application, how to get started with that you can see it here.

like image 77
trisek Avatar answered Oct 26 '22 06:10

trisek