Create a simple modal window in Angular

Yurii K
Nerd For Tech
Published in
3 min readOct 26, 2022

It is hard to imagine an application without modal windows. Windows are very important if you want to ask a yes/no question or just give a short information.

In this article, I will show how we can create our own modal window and extend it to your needs if necessary.

We need to create a modal window component and a couple of services for our modal window system.

We have two dialog services. We can use only one but those two services give us space in the future. We could have different modal windows with charts or tables or a form. All those dialog windows will use different components with different data types.
Dialog service gives us space to extend itself and use different modal window components. Dialog storage service just sends data to the modal window component. The first service prepares data for the modal window, and the second service sends the prepared data to the modal window component.

In this article, we will create a simple modal window. The model for this window looks like this.

The most interesting thing here is the button model. This model has a click handler and data property. Basically, when the user clicks on the button it will return this button with data from the modal window.

Dialog storage service is a simple service with a subject to send data for modal windows.

As I said before, the dialog service prepares a dialog modal for the dialog component and sends this information through the dialog storage service. In functions showDialogCancelOk and showDialogOk we create a handler with a subject. That is how we make a subscription and send results to components that use our dialog service.

Now we can make a modal dialog component. In this component, we subscribe to a dialog storage service to receive data and send the result of user choice.

All interesting stuff about modal windows is written in an SCSS file. Here we use z-index to be on top of everything. In HTML we have a modal background. This background takes up the whole space of the browser window. The modal body we set to be in the center of the browser window.

The modal window infrastructure is ready, it is time to check how it works. Of course, we put all services and components in the main module. The next step is to add a modal window CSS selector in our app component.

Our modal window is ready.

If you need to take a close look at the project here is the link.

Originally published at http://tomorrowmeannever.wordpress.com on October 26, 2022.

--

--

Yurii K
Nerd For Tech

Full-stack developer. In my work, I use Angular and C#. In my free time I write articles for my blog.