DEV Community

Cover image for Building a dialog(Material) service in angular
devashishSarmah
devashishSarmah

Posted on

Building a dialog(Material) service in angular

In angular development, the typical way we open a dialog is by injecting MatDialog directly into a component.

MatDialog injected into a component

First scenario diagram

This implementation will be okay for a dialog that will be opened by a single component.
But in the case of a kind of dialog that will be used by many components that belongs to different modules in the application, This approach won't work.

One of the solutions can be a dialog service whose responsibilities will be:

  1. Take the inputs from the component(Which invokes the opening of the dialog).

  2. Opens the dialog and passes the inputs to the dialog or stores the inputs as its member variable.

  3. Returns the dialogRef to the component(Which invokes the opening of the dialog).

Dialog service based solution

  • A dialog module needs to be created which will hold the dialog Component and other modules that are required in the dialog component.

  • The components that require to open the dialog will need to import the dialog module first.

Dialog Service

The Dialog Module

Dialog Module

Importing the dialog module to the dedicated module that the component which will open the dialog resides in (In my case the app module)

App Module

The implementation of the open procedure in a component.

App component

We can also send out the data through the method parameter that we have defined in the service for the DialogConfig.

Another way to send data to dialog

The entire source code is available on: https://github.com/devashishSarmah/dialog-service

Thanks for checking out.
Please feel free to comment for any queries

Top comments (1)

Collapse
 
oliverdjbrown profile image
Oliver Brown

excellent article and help me alot thanks