Creating a dialog in two lines of code

The theme of our week so far is that we don’t always need to think just in terms of components. We saw that directives and CSS selectors can be powerful tools to keep in mind.

Today, I’m going to show how modern HTML and template reference variables can do a lot of work for us with very little code.

Dialogs and modal windows have been a pain to work with for a very long time on the web. Not anymore though.

Here are a few lines of code that makes it all work painlessly:

dialog is a modern addition to HTML with a simple API: show(), showModal(), close(). The above code creates a template reference variable #dialog to get access to the dialog element, and then we call dialog.showModal() to open a modal window. That’s it. No dependency is needed, no CSS trick to create an overlay, no component library, and no jQuery.

Here is a link to a fully working example and a slighter longer tutorial with styling information for HTML dialogs.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.