Sub topic 15
Dispatching events from a modal to its opener
This chapter assumes you can build a modal that extends LightningModal, open it with open(), and return a value with this.close(). You should also be comfortable with CustomEvent and arrow functions.
Why close() is not always enough
this.close(result) resolves the Promise returned by open(). That happens once, and it ends the modal. Sometimes the opener needs to hear from the modal while it is still open. Examples:
- A filter modal updates a list behind it as the user changes options.
- A picker previews the selected value in the opener.
- A multi-step wizard reports progress.
For these cases the modal dispatches a custom event, and the opener handles it while the modal stays on screen.
| Mechanism | Fires | Ends the modal | Carries |
|---|---|---|---|
| `this.close(result)` | Once | Yes | One result value |
| `this.dispatchEvent(...)` | Any number of times | No | `event.detail` |
Why the template cannot listen
A modal is rendered in an overlay that Salesforce attaches outside your component's DOM. It is not a child element in your opener's template. You cannot write <c-priority-modal onprioritychange={...}>, because that tag never appears in your markup.
Instead, you pass the handler as an option to open(). Any option whose name starts with on is registered as a listener for the event named after that prefix. An option called onprioritychange listens for an event named prioritychange.
Building the modal
This modal lets the user pick a priority. Each click dispatches an event. The Save and Cancel buttons close the modal.
<template>
<lightning-modal-header label={label}></lightning-modal-header>
<lightning-modal-body>
<template for:each={items} for:item="item">
<lightning-button
key={item.value}
label={item.value}
data-value={item.value}
variant={item.variant}
onclick={handleSelect}
class="slds-m-right_x-small"
></lightning-button>
</template>
</lightning-modal-body>
<lightning-modal-footer>
<lightning-button label="Cancel" onclick={handleCancel}></lightning-button>
<lightning-button variant="brand" label="Save" onclick={handleSave}></lightning-button>
</lightning-modal-footer>
</template>import { api } from 'lwc';
import LightningModal from 'lightning/modal';
const OPTIONS = ['Low', 'Normal', 'High'];
export default class PriorityModal extends LightningModal {
@api currentPriority;
selected;
connectedCallback() {
this.selected = this.currentPriority;
}
get items() {
return OPTIONS.map((value) => ({
value,
variant: value === this.selected ? 'brand' : 'neutral'
}));
}
handleSelect(event) {
this.selected = event.target.dataset.value;
this.dispatchEvent(
new CustomEvent('prioritychange', {
detail: { value: this.selected }
})
);
}
handleCancel() {
this.close('cancel');
}
handleSave() {
this.close('save');
}
}Three details matter here:
currentPriorityis a public property, so the modal copies it into the private fieldselectedinstead of changing it. A component should not write to its own@apiproperties.- The event has no
bubblesorcomposedflags. The handler is attached to the modal's own instance, so the event does not need to travel through the DOM. - The event name is
prioritychange. It is lowercase, with no hyphens or uppercase letters. This matters in the next section.
Handling the event in the opener
The opener passes onprioritychange in the same options object that holds size, label, and the @api values.
import { LightningElement } from 'lwc';
import PriorityModal from 'c/priorityModal';
export default class PriorityPicker extends LightningElement {
priority = 'Normal';
preview = 'Normal';
async handleOpen() {
const result = await PriorityModal.open({
size: 'small',
description: 'Choose a priority for this case',
label: 'Choose priority',
currentPriority: this.priority,
onprioritychange: (event) => {
event.stopPropagation();
this.preview = event.detail.value;
}
});
if (result === 'save') {
this.priority = this.preview;
} else {
this.preview = this.priority;
}
}
}<template>
<lightning-card title="Case priority">
<div class="slds-var-p-around_medium">
<p>Saved: {priority}</p>
<p>Preview: {preview}</p>
<lightning-button label="Change priority" onclick={handleOpen}></lightning-button>
</div>
</lightning-card>
</template>While the modal is open, "Preview" changes with every click. The "Saved" value changes only after the user clicks Save. If the user cancels, or closes the modal with the X button or Escape, result is not 'save' and the preview resets.
The handler is an arrow function, so this refers to the opener component. A regular function would lose that binding. The call to event.stopPropagation() keeps the event from propagating further after your handler has dealt with it.
Choosing between an event and a result
Use events for changes you want to react to immediately and that you can safely repeat. Use the close result for the final decision. In the example, the events drive a preview, and the close result decides whether to keep it.
Do not put the only copy of important data in an event. If the user dismisses the modal with Escape, no further events fire and open() resolves with undefined. Anything you must persist should be in the data returned by close(), or saved by the modal itself before it closes.
Common errors
- The handler never runs. The usual cause is a mismatch between the event name and the option name. Dispatching
prioritychangerequiresonprioritychange. Check spelling and case first. - Putting the handler in the template. Writing
onprioritychangeon a tag in your HTML does nothing, because the modal is not in your template. thisis undefined or wrong in the handler. Use an arrow function, or bind the method before passing it.- Updating the UI after the modal is gone. Events stop once the modal closes. Do the final update after
await, using the close result. - Expecting a return value from the handler. The handler's return value is ignored. To send data back to the modal, use an
@apiproperty set atopen()time or have the modal read shared state.
Exercise
A modal dispatches new CustomEvent('itemadded', { detail: { id } }). Write the option you would pass to open() to handle it, and explain why you cannot handle it with onitemadded on a tag in the opener's template.
Show answer
Pass onitemadded: (event) => { event.stopPropagation(); /* use event.detail.id */ } in the options object of open(). The modal renders in an overlay outside the opener's DOM, so no element in the opener's template represents it. The on plus event name option is the only way to attach a listener to the modal instance.
Exercise
In the priority example, the user clicks High, then Low, then presses Escape. What is the value of priority afterwards, and what is the value of preview?
Show answer
priority keeps its previous value, for example Normal. Escape closes the modal without calling close('save'), so open() resolves with undefined, which is not 'save'. The else branch resets preview to priority, so both values are Normal.