Sub topic 13
Opening a modal and passing options and properties
This chapter covers the open() method of a LightningModal component: which options it accepts, how to pass values into the modal's @api properties, and what the returned Promise gives you. It assumes you know basic LWC structure, @api decorators, and async/await. It also assumes you have already built a modal class that extends LightningModal and a template with header, body and footer components.
How open() works
A modal component never appears by being placed in a parent's template. The parent imports the modal class and calls its static open() method.
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
}
}
}open() takes one object. It returns a Promise. The Promise resolves when the modal closes, and its value is whatever the modal passed to this.close(). Because of this, await works well here. The code after await runs only after the user has dismissed the modal.
Two kinds of keys in the options object
The object you pass to open() mixes two kinds of keys.
| Kind | Examples | What it does |
|---|---|---|
| Modal options | `size`, `description`, `label`, `disableClose` | Controls the modal frame |
| Your properties | `recordName` | Sets the modal's own `@api` properties |
Any key that is not a built-in option is assigned to an @api property with the same name on the modal. In the example above, recordName sets @api recordName on ConfirmDeleteModal.
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 template reads {recordName} and {label}:
<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>label is not declared in the modal class, yet the template can use it. The LightningModal base class already defines label, size, description and disableClose as @api properties, so you do not redeclare them.
The built-in options
sizesets the width. Accepted values aresmall,medium,largeandfull. The default ismedium.descriptionis accessible text that screen readers announce when the modal opens. Always set it. It should say what the modal is for, in a full sentence such as "Confirm deletion of the selected record".labelis the heading text. The modal header component displays it when you bindlabel={label}. If you leavelightning-modal-headerout, the label is not shown.disableCloseprevents the user from dismissing the modal with the close button, the Escape key, or a click outside. Use it while a save is running. Set it back tofalsewhen the user may leave. The modal can change it at run time throughthis.disableClose.
Passing values in
You can pass strings, numbers, booleans, arrays and objects. The modal receives them as @api properties. Treat them as read-only inside the modal, the same as any public property in LWC. If the modal needs to change a value, copy it into a private field first.
import { api } from 'lwc';
import LightningModal from 'lightning/modal';
export default class EditNoteModal extends LightningModal {
@api initialNote;
draft;
connectedCallback() {
this.draft = this.initialNote;
}
handleChange(event) {
this.draft = event.target.value;
}
handleSave() {
this.close(this.draft);
}
}The @api values are set before connectedCallback runs, so reading them there is safe.
Handling the result
The resolved value is your return channel. Choose a consistent shape so the opener can tell the cases apart.
import { LightningElement } from 'lwc';
import EditNoteModal from 'c/editNoteModal';
export default class NoteHost extends LightningElement {
note = 'First draft';
async handleEdit() {
const result = await EditNoteModal.open({
size: 'medium',
description: 'Edit the note text',
label: 'Edit note',
initialNote: this.note
});
if (result !== undefined) {
this.note = result;
}
}
}If the user dismisses the modal with the close button or Escape, the Promise still resolves, with undefined. It does not reject. So result !== undefined separates "saved" from "dismissed". In the confirm example, the explicit 'cancel' string covers the Cancel button, while undefined covers every other way out. Always compare against the exact success value, as in result === 'confirm', rather than checking that the result is truthy.
Sequence of a modal call
Common errors
- Calling
open()on an instance.open()is static. CallConfirmDeleteModal.open(...), using the imported class, notthis.template.querySelector(...). - Forgetting
async. Usingawaitin a method that is not declaredasyncis a syntax error. Alternatively, use.then(). - Mutating an
@apivalue. Assigning tothis.recordNameinside the modal triggers a read-only warning. Copy it first. - Missing
description. The modal still opens, but screen reader users get no context. - Treating dismissal as an error. Wrapping
open()intry/catchdoes not catch a dismissed modal. Check forundefinedinstead. - Opening from a non-user context. Open modals in response to a user action such as a click, not during
connectedCallback. A modal appearing on load surprises users and is hard to test.
Exercise
A parent calls const result = await MyModal.open({ size: 'large', label: 'Pick a color', color: 'red' });. Which of the three keys are built-in modal options, which sets an @api property you must declare yourself, and what is result if the user presses Escape?
Show answer
size and label are built-in options (the base class already provides them as @api properties). color is not built in, so MyModal must declare @api color; for the value to arrive. If the user presses Escape, the Promise resolves with undefined, so result is undefined. It is not rejected.
Exercise
Write the check in the opener that runs a save only when the modal returned the string 'confirm', and does nothing when the user cancels or dismisses it.
Show answer
if (result !== 'confirm') { return; } placed right after the await, or equivalently if (result === 'confirm') { /* save */ }. Both ignore 'cancel' and undefined.