Create a Dialog Component Using the Native Dialog Element in Angular

Netanel Basal
Netanel Basal
Published in
2 min readMay 2, 2022

In this article, we’ll create a dialog component by using the new dialog element, which is already supported by all major browsers. Our API will be template-driven:

We’ll create a dialog component and use an attribute selector. The dialog element will serve as the host, and the component template will be appended to it:

The header, content, and footer will be rendered using ng-templates so that they’ll be initialized only when the modal is opened. Let’s create the directives:

Now, let’s render the templates in the dialog component template:

In addition, we provide a title input in case nothing special is needed in our dialog header. Next, we need to provide a showDialog() method to render the templates and open the dialog:

Now we need to create the close() method which destroys the templates and closes the dialog:

Using the cancel event, we can also close it when the user clicks escape:

One last thing is to be able to close the dialog when clicking on the backdrop:

We’ll also feature animation upon closing the dialog box:

You can read about this technique in one of my previous articles. The complete code is available on stackblitz.

In our case, we used a template-driven approach, but a code-driven approach would also be possible:

Follow me on Medium or Twitter to read more about Angular and JS!

--

--

Netanel Basal
Netanel Basal

Written by Netanel Basal

A FrontEnd Tech Lead, blogger, and open source maintainer. The founder of ngneat, husband and father.

Responses (3)