Sub topic 11
LightningModal basics
A modal is a dialog that opens on top of the page and blocks interaction with everything behind it until the user closes it. In Lightning Web Components (LWC), you build one by extending LightningModal, a base class from the lightning/modal module. This chapter covers what the base class gives you, the files a modal needs, and the rules that most often cause errors.
This chapter assumes you already know the basic LWC file structure (HTML template, JavaScript class, metadata file), the @api decorator, and JavaScript Promises with async/await. Later chapters cover the template structure, the open options, and the close result in more detail. Here you build the foundation.
What LightningModal is
LightningModal is a class you extend instead of LightningElement. A component that extends it is a modal component. It is not placed in another component's template. Instead, another component opens it by calling a static method.
The base class provides these members:
| Member | Kind | Purpose |
|---|---|---|
| `open(options)` | Static method | Opens the modal and returns a Promise |
| `close(result)` | Instance method | Closes the modal and resolves the opener's Promise with `result` |
| `disableClose` | Instance property | When `true`, blocks the close button and the Escape key |
| `size`, `label`, `description` | Open options | Control the width, the header text, and the accessible description |
The label, size, description, and disableClose values are options you pass to open(). They are inherited by the modal instance, so you do not declare them yourself.
The three files of a modal
A modal component has the same three files as any other component. This example is a confirmation dialog named confirmDeleteModal.
The template uses three child components as its top-level content.
<template>
<lightning-modal-header label={label}></lightning-modal-header>
<lightning-modal-body>
<p>Delete {recordName}? This cannot be undone.</p>
</lightning-modal-body>
<lightning-modal-footer>
<lightning-button label="Cancel" onclick={handleCancel}></lightning-button>
<lightning-button variant="destructive" label="Delete" onclick={handleConfirm}></lightning-button>
</lightning-modal-footer>
</template>The JavaScript class extends LightningModal. It receives values through @api properties and calls this.close() to finish.
import { api } from 'lwc';
import LightningModal from 'lightning/modal';
export default class ConfirmDeleteModal extends LightningModal {
@api recordName;
handleCancel() {
this.close('cancel');
}
handleConfirm() {
this.close('confirm');
}
}The metadata file is the usual one. Modals do not need any targets entry, because they are never placed on a page.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/soap/2006/04/metadata">
<apiVersion>62.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>Notice that {label} in the header comes from the label option passed to open(). The modal class does not declare label, because the base class already defines it.
Opening the modal
A different component imports the modal class and calls its static open() method. The call returns a Promise. The Promise resolves when the modal closes, and its value is whatever the modal passed to close().
import { LightningElement } from 'lwc';
import ConfirmDeleteModal from 'c/confirmDeleteModal';
export default class ModalOpener extends LightningElement {
async handleDeleteClick() {
const result = await ConfirmDeleteModal.open({
size: 'small',
description: 'Confirm deletion of the selected record',
label: 'Confirm delete',
recordName: 'Acme Corp'
});
if (result === 'confirm') {
// continue with the delete
}
}
}The object passed to open() mixes two kinds of keys. size, description, and label configure the modal itself. Any other key, such as recordName, sets the @api property of the same name on the modal instance.
How the pieces connect
The sequence below shows what happens from the click to the result.
The opener never reads the modal's state directly. The only data that comes back is the one value passed to close(). If you need to return several values, pass an object, for example this.close({ action: 'save', name: this.name }).
What happens if the user dismisses the modal
Users can usually close a modal with the X button in the header or the Escape key, without clicking any of your buttons. In that case the Promise still resolves, but with undefined, because no result was passed to close().
This is why the opener in the example checks result === 'confirm' instead of result !== 'cancel'. Comparing against the one value that means "proceed" treats dismissal and cancellation the same way, and both do nothing. Writing the check the other way round would let a dismissed dialog fall through into the destructive branch.
Common errors
- Extending
LightningElementinstead ofLightningModal. The component then has noclose()method, and callingopen()on it fails because the static method does not exist. - Calling
open()on an instance.open()is static. UseConfirmDeleteModal.open(...), notnew ConfirmDeleteModal().open(...). - Forgetting
await. Without it, the variable holds a pending Promise. A check such asresult === 'confirm'is then always false. - Mixing top-level content. The template should contain only the header, body, and footer components. Content placed directly inside
<template>outside them does not get the standard modal layout. - Passing a value with no matching
@apiproperty. The value is not available in the template. Declare@api recordName;for every custom key you pass. - Using
lightning-modal-headerwithout a label. The header renders empty and the dialog has no visible title. Passlabeltoopen(), or omit the header only if you have another accessible title.
Controlling dismissal
Sometimes the user must make a choice, such as accepting terms. Set disableClose to true in the modal to block the X button and the Escape key. You can set it from code while an operation runs, then turn it back off.
import { api } from 'lwc';
import LightningModal from 'lightning/modal';
export default class SaveModal extends LightningModal {
@api recordName;
async handleSave() {
this.disableClose = true;
try {
await this.saveSomething();
this.close('saved');
} finally {
this.disableClose = false;
}
}
saveSomething() {
return new Promise((resolve) => setTimeout(resolve, 500));
}
}While disableClose is true, the user cannot dismiss the dialog. Your own this.close() call still works. Use this setting briefly. A modal that cannot be closed for a long time frustrates users.
Exercise
A parent component calls await MyModal.open({ size: 'small', label: 'Edit', accountName: 'Acme' }). The modal class declares only @api recordId;. The user presses Escape. What value does await produce, and why is accountName unavailable in the modal?
Show answer
The await produces undefined, because the modal closed without this.close(result) being called with a value. accountName is unavailable because custom keys in the open() options only reach the modal through a matching @api property, and the modal declares only recordId. Adding @api accountName; fixes it.
Exercise
You want a modal to return both the action the user chose and the text they entered. How do you return both from the modal, and how does the opener read them?
Show answer
Pass one object to close(), for example this.close({ action: 'save', text: this.text }). The opener reads it from the awaited result: const result = await MyModal.open({...}); if (result && result.action === 'save') { use(result.text); }. Checking result first handles the dismissed case, where the result is undefined.