How to create Modal/Popup in Lightning Web Component

by Rijwan Mohmmed
How-to-modal-in Lightning-web-component-LWC-Salesforce

Hello friends today we will learn how to show modal/popup in Lightning Web Component. We use Modal to show some extra info or edit the record etc.

How-to-create-Modal-Popup-in-Lightning-Web-Component(LWC)

modal.html :

<template>
	<lightning-card variant="Narrow" title="Hello" icon-name="standard:account">
		<lightning-button label="Open Modal" slot="actions" onclick={openModal}></lightning-button>
		<p class="slds-p-horizontal_small">Card Body Narrow (custom component)</p>
	</lightning-card>

	<!-- modal start -->
	<template if:true={ShowModal}>
		<section role="dialog" tabindex="-1" aria-labelledby="modal-heading-01" aria-modal="true"
			aria-describedby="modal-content-id-1" class="slds-modal slds-fade-in-open">
			<div class="slds-modal__container">
				<!-- modal header start -->
				<header class="slds-modal__header">
					<button class="slds-button slds-button_icon slds-modal__close 
                              slds-button_icon-inverse" title="Close" onclick={closeModal}>
                  <lightning-icon icon-name="utility:close"
                     alternative-text="close"
                     variant="inverse"
                     size="small" ></lightning-icon>
                  <span class="slds-assistive-text">Close</span>
               </button>
					<h2 id="modal-heading-01" class="slds-text-heading_medium slds-hyphenate">
						Modal Header
					</h2>
				</header>
				<!-- modal body start -->
				<div class="slds-modal__content slds-p-around_medium" id="modal-content-id-1">
					<p>
						Hello friends today we will learn how to show modal/popup in Lightning Web Component. We use Modal to show
						some extra info or edit the record etc.
					</p>
				</div>

				<!-- modal footer start-->
				<footer class="slds-modal__footer">
					<lightning-button label="Cancel" title="Non-primary action" onclick={closeModal} class="slds-m-left_x-small">
					</lightning-button>
					<lightning-button variant="brand" label="Save" title="Primary action" onclick={handleClick}
						class="slds-m-left_x-small">
					</lightning-button>
				</footer>

			</div>
		</section>
		<div class="slds-backdrop slds-backdrop_open"></div>
	</template>

	<!-- modal end -->
</template>

modal.js :

import { LightningElement } from "lwc";

export default class modal extends LightningElement {
    ShowModal = false;
  
    openModal() {    
        // to open modal 
        this.ShowModal = true;
    }
 
    closeModal() {    
        // to close modal 
        this.ShowModal = false;
    }

    handleClick(){

        //do something
    }
}

What’s your Reaction?
+1
1
+1
0
+1
0
+1
0
+1
0
+1
0

You may also like

Leave a Comment