Sub topic 15
Dispatching events from a modal to its opener
This chapter assumes you can write a LightningModal component and open it with open(). It also assumes you know how CustomEvent works.
Why use events
close() returns one value, and only when the modal ends. Sometimes the opener needs data while the modal is still open. Examples are applying a filter as the user changes it, or refreshing a list after each step of a wizard. For these cases the modal dispatches a custom event, and the opener listens for it.
Dispatch from the modal
The modal calls this.dispatchEvent with a CustomEvent. This works the same way as in any other component.
<template>
<lightning-modal-header label={label}></lightning-modal-header>
<lightning-modal-body>
<lightning-button label="Show open accounts" onclick={handleApply}></lightning-button>
</lightning-modal-body>
<lightning-modal-footer>
<lightning-button label="Done" onclick={handleDone}></lightning-button>
</lightning-modal-footer>
</template>import LightningModal from 'lightning/modal';
export default class FilterModal extends LightningModal {
handleApply() {
this.dispatchEvent(
new CustomEvent('filterchange', {
detail: { status: 'open' }
})
);
}
handleDone() {
this.close('done');
}
}Listen in the opener
In the options passed to open(), add a property named on plus the event name. Here the event is filterchange, so the property is onfilterchange. The value is a function that receives the event.
import { LightningElement } from 'lwc';
import FilterModal from 'c/filterModal';
export default class FilterOpener extends LightningElement {
filter;
async handleOpen() {
const result = await FilterModal.open({
size: 'small',
description: 'Choose how to filter the account list',
label: 'Filter accounts',
onfilterchange: (event) => {
event.stopPropagation();
this.filter = event.detail;
}
});
// result is 'done' once the modal closes
}
}Use an arrow function so this still refers to the opener. The handler runs each time the event fires. The await finishes only when the modal calls close().
Common errors
- Wrong handler name. The property must be
onfollowed by the exact event name in lowercase.onFilterChangewill not match an event namedfilterchange. - Using
functioninstead of an arrow function. The handler then loses the opener'sthis, andthis.filteris not set on your component. - Expecting events after close. Once the modal closes, the component is removed. Dispatch events before you call
close(). - Putting data in the event when it belongs in the result. Use events for updates during the session. Use the
close()value for the final answer.
Exercise
A modal dispatches new CustomEvent('itemselected', { detail: 42 }). What property do you add to the open() options so the opener receives it, and when does await Modal.open(...) finish?
Show answer
Add onitemselected: (event) => { ... }, and read the value from event.detail. The await finishes when the modal calls this.close(result), not when the event fires.