How to display a modal window using lightning web components

We will go through building a reusable lightning web component that you can use to show modal windows in other LWC components.

Use cases

  • Display modal window or popup window in user interface


Explanation

We can use lightning design system sample modal code in the link to show the modal window. But to implement opening and closing behavior of the modal, we need to use javascript variables in lwc. We will create a reusable lwc component with name "utilModal". This will have code needed to show and hide modal window. Then we will create a sample parent component with name "modalParentExample" that we can use embed modal component. We fire custom events from utilModal component and parent "modalParentExample" catches these events. Parent component can use these action handlers to execute actions when buttons in modal window are clicked.

How to use

  • Create an LWC component with name utilModal
  • Copy content from above code to utilModal component. utilModal.html is the HTML file and utilModal.js is the Javascript file
  • "modalParentExample" has sample code to open modal window

4 comments:

  1. I added the utilModal component in container component and invoked from there but the popup modal heading is rendered with thicker text after 1 sec it becomes lighter. Why?

    ReplyDelete
    Replies
    1. It might be because the css is getting loaded later. Are you loading any css from static resource?

      Delete
  2. Nice and good article. It is very useful for me to learn and understand easily. Thanks for sharing
    ServiceNow Developer Training Online
    ServiceNow Admin Training Online

    ReplyDelete