Sub topic 7
Detecting content changes with slotchange
A child component often needs to know what its parent put into a slot. A card may need to hide an empty footer. A list may need to show an item count or an empty-state message. The slotchange event provides this signal. This chapter covers when it fires, what it carries, how to read the slot's content from the handler, and the mistakes that stop it from working.
It assumes you can write a child component with a default slot and named slots, pass content from a parent with the slot attribute, and attach event handlers in a template. It also assumes you know that slotted markup is owned by the parent.
What slotchange is
slotchange is a standard DOM event. The browser fires it on a <slot> element when that slot's list of assigned nodes changes. Assigned nodes are the nodes the parent supplied for that slot. Three kinds of change trigger it:
- A node is assigned to the slot, for example the parent starts rendering an element with
slot="footer". - A node is removed from the slot, for example a
lwc:ifblock in the parent turns false. - A slotted node's
slotattribute changes so that it moves to a different slot.
The event has these properties:
- It does not carry the new content. The event object is a plain
Event. You read the content from the slot. - It bubbles but is not composed. It travels up through the child's own template and stops at the shadow boundary. A parent component cannot listen for the child's
slotchange. event.targetis the<slot>element, so the handler can callevent.target.assignedNodes().- It is delivered asynchronously. The browser queues it and dispatches it after the current task's synchronous work, not at the moment the DOM changes.
You attach the handler in the child's template with onslotchange, the same way you attach onclick.
Wiring the handler
The card component from earlier chapters has a footer slot. Here the footer slot reports changes:
<!-- card.html (footer section) -->
<footer class={footerClass}>
<slot name="footer" onslotchange={handleFooterChange}></slot>
</footer>// card.js
import { LightningElement } from 'lwc';
export default class Card extends LightningElement {
hasFooter = false;
handleFooterChange(event) {
const slot = event.target;
this.hasFooter = slot.assignedNodes().length > 0;
}
get footerClass() {
return this.hasFooter ? 'footer' : 'footer slds-hide';
}
}The handler reads assignedNodes() from the slot that fired the event and stores a boolean. Because hasFooter is a field, assigning a new value makes the component re-render, and the getter returns the other class string. The footer starts hidden. It appears only after the browser reports that something was assigned.
The footer container is hidden with CSS and is never removed from the DOM. This matters, and a later section explains why.
The event cycle
The diagram shows what happens between a parent's change and the child's re-render.
The parent can finish rendering before the child learns anything. The child's first render happens with default field values, and the handler runs afterward. Choose initial values that look acceptable for that first pass. In the card, "no footer" is the safe default.
What does and does not fire
The event reports changes to the list of assigned nodes. It does not report changes inside those nodes. This table shows the common cases.
| Change in the parent | Does slotchange fire? |
|---|---|
| An element with `slot="footer"` first appears | Yes |
| That element is removed | Yes |
| The text inside a slotted element changes | No |
| An attribute or class on a slotted element changes | No |
| A new item is added to a `for:each` that renders slotted elements | Yes |
| An item's field changes but the item stays in the list | No |
| An element's `slot` attribute changes to another slot name | Yes, on both slots |
| The slot has only fallback content from the start | No |
| Parent removes the only assigned node, so fallback content shows | Yes |
The last two rows matter for fallback content. A slot with no assigned nodes and only fallback content never fires on its own at startup, because nothing changed. The fallback is not an assigned node. If the parent fills the slot and then empties it, the event fires both times, and assignedNodes() returns an empty array on the second call.
Reading what was assigned
HTMLSlotElement has three methods for reading assigned content.
| Method | Returns | Notes |
|---|---|---|
| `assignedNodes()` | Elements and text nodes assigned to the slot | Empty array when only fallback content shows |
| `assignedNodes({ flatten: true })` | Assigned nodes, with nested slots expanded | Returns the fallback content when nothing is assigned |
| `assignedElements()` | Only element nodes | Skips text nodes, so counting is simpler |
Use assignedElements() when you count items or look for particular components. Use assignedNodes() when text matters, for example when a slot should count as filled if it contains only a text string.
flatten: true matters in two places. The first is fallback content. assignedNodes() returns [] for a slot with fallback only, but assignedNodes({ flatten: true }) returns the fallback nodes. If you use flatten: true to decide whether the parent supplied content, an empty slot with fallback text looks filled. For "did the parent supply anything" checks, the plain call is correct. The second place is a slot that a parent forwards into another component's slot. A later chapter covers forwarding, and there flatten: true lets you see the content that finally lands in the innermost slot.
A common pattern is to read the elements and then use their public API:
handleSlotChange(event) {
const items = event.target.assignedElements();
items.forEach((item, index) => {
// Only @api properties are a stable contract with the slotted component.
item.position = index + 1;
});
}Setting an @api property on a slotted component is the supported way for a child to communicate with it. Changing classes or attributes on elements the parent owns is fragile. The parent's next render can overwrite your changes.
A worked example: an item list with a count
The next example shows the full path from a parent's data to a child's state. The child is a list container that shows how many items it received.
<!-- itemList.html -->
<template>
<p lwc:if={isEmpty} class="status">No items yet.</p>
<p lwc:else class="status">{itemCount} item(s)</p>
<ul>
<slot onslotchange={handleSlotChange}></slot>
</ul>
</template>// itemList.js
import { LightningElement } from 'lwc';
export default class ItemList extends LightningElement {
itemCount = 0;
handleSlotChange(event) {
this.itemCount = event.target.assignedElements().length;
}
get isEmpty() {
return this.itemCount === 0;
}
}The parent owns the data and renders the list items into the default slot:
<!-- itemsDemo.html -->
<template>
<lightning-button label="Add item" onclick={handleAdd}></lightning-button>
<lightning-button label="Clear" onclick={handleClear}></lightning-button>
<c-item-list>
<li for:each={items} for:item="item" key={item.id}>{item.name}</li>
</c-item-list>
</template>// itemsDemo.js
import { LightningElement } from 'lwc';
export default class ItemsDemo extends LightningElement {
items = [];
nextId = 1;
handleAdd() {
const id = this.nextId++;
this.items = [...this.items, { id, name: `Item ${id}` }];
}
handleClear() {
this.items = [];
}
}Each click on "Add item" produces a new array. The parent re-renders and adds an li to the slot. The slot fires slotchange, and the handler recounts and updates itemCount. "Clear" removes every li, so the count returns to 0 and the empty message shows.
Two details are easy to miss:
- The handler recounts on every event. It does not try to work out what changed. This is simple and correct, and the cost is small for realistic list sizes.
- If the parent edits the name of an existing item, the child sees no event, and the count stays correct. The text change is the parent's own re-render of an
liit owns.
Several slots, one handler
A component with several slots can share one handler. Identify the slot from the event:
<!-- panel.html -->
<template>
<header class={headerClass}>
<slot name="header" data-slot="header" onslotchange={handleSlotChange}></slot>
</header>
<div class="body">
<slot></slot>
</div>
<footer class={footerClass}>
<slot name="footer" data-slot="footer" onslotchange={handleSlotChange}></slot>
</footer>
</template>// panel.js
import { LightningElement } from 'lwc';
export default class Panel extends LightningElement {
hasHeader = false;
hasFooter = false;
handleSlotChange(event) {
const filled = event.target.assignedNodes().length > 0;
if (event.target.dataset.slot === 'header') {
this.hasHeader = filled;
} else {
this.hasFooter = filled;
}
}
get headerClass() {
return this.hasHeader ? 'header' : 'header slds-hide';
}
get footerClass() {
return this.hasFooter ? 'footer' : 'footer slds-hide';
}
}event.target is the slot that fired, so event.target.dataset.slot tells you which one. Separate handlers are also fine. Use a shared handler when the logic is identical and only the target field differs.
Pitfalls
Do not conditionally render the slot
The <slot> element must be in the DOM to receive content. If you wrap a slot in lwc:if, the slot does not exist while the condition is false. The parent's content has nowhere to go and never reaches the child. The event never fires either, so the condition that depends on the event can never become true.
<!-- Broken: footerVisible depends on slotchange, but the slot is not rendered until it is true -->
<template lwc:if={footerVisible}>
<footer>
<slot name="footer" onslotchange={handleFooterChange}></slot>
</footer>
</template>Keep the slot rendered and hide its container with CSS, as the card does with slds-hide.
Do not read slot content too early
At connectedCallback the slot does not exist yet. In renderedCallback the slot exists, but the browser may not have assigned content. Reading assignedNodes() in renderedCallback can work in one case and fail in another, depending on render order. The handler for slotchange is the reliable place for the initial read. If you also need a first read for a slot that may be empty, remember that an empty slot does not fire at startup. Give the field a default that matches "empty".
Do not assume the event reaches the parent
The event is not composed. The parent that supplies the slotted content cannot add onslotchange to <c-card> and receive it. If the parent needs to know, the child handles slotchange and then dispatches its own CustomEvent with the information the parent needs.
Avoid loops through the slotted content
Suppose the handler changes the parent's content, for example through an @api method that makes the parent render more items. That causes another slotchange, which runs the handler again. Make the handler idempotent. It should read the current state and set a field. It should not add or remove slotted nodes.
Do not count text nodes by accident
assignedNodes() includes text nodes. The LWC template compiler removes whitespace-only text between elements in the parent's template, so this usually does not show up. A parent that places a text string in the slot, or an expression that renders text, adds a text node. When you count components or elements, use assignedElements().
Update only when the value changes
Assigning the same primitive value to a field does not cause a meaningful re-render, so a handler that sets hasFooter = true repeatedly is harmless. Assigning a new array or object on every event does cause re-renders. If the handler stores a list of the elements, compare the length or the identities first, or store only the data you need, such as a count.
Decision checklist
Use slotchange when the child's own rendering depends on whether or how much content the parent supplied. Examples are hiding empty regions, showing empty states, and numbering slotted children through their @api properties. Use another approach in these cases:
- You need to know what text a slotted element contains. Have the parent pass that value in a property.
- You need to react when slotted data changes. The parent owns the data, so the parent should call an
@apimethod or set a property on the child. - You need the parent to hear about the change. Dispatch a custom event from the child.
Exercise
A child component renders <slot name="actions" onslotchange={handleChange}></slot>. The parent initially renders no element with slot="actions". The child stores hasActions = false and computes a CSS class from it. When does handleChange first run?
Show answer
It runs the first time the parent assigns a node to the slot, for example when a lwc:if in the parent turns true. If the slot has no assigned nodes from the start, no change happens, so no event fires. That is why hasActions needs a default of false that matches the empty state.
Exercise
A parent changes the text of a slotted <span slot="header"> from "Draft" to "Final". Does the child's slotchange handler run? Explain, and say how the child could still react.
Show answer
No. The span stays assigned to the slot, so the list of assigned nodes is unchanged. slotchange reports membership changes, not changes inside a slotted node. The child could expose an @api property such as status, and the parent could set it. Another option is for the parent to wrap the content in a component that dispatches its own event.
Exercise
A developer wraps the footer slot in <template lwc:if={hasFooter}> and sets hasFooter inside the slotchange handler. The footer never appears. Why, and what is the fix?
Show answer
The slot is not rendered while hasFooter is false, so the parent's content is never assigned to it and slotchange never fires. hasFooter can never become true. Render the slot always and hide the container with a CSS class, such as slds-hide, computed from hasFooter.
Exercise
You want to count the slotted <c-tab> components in a default slot. Which method do you call on event.target, and why not assignedNodes()?
Show answer
Call assignedElements(). It returns only element nodes. assignedNodes() also returns text nodes, so a stray text string in the parent's markup would inflate the count.