Sub topic 8
Reading slotted nodes from the child
A child component often needs to know what the parent put into its slots. It might hide an empty footer, count the items it was given, or focus the first field. This chapter covers how the child can read slotted content, when to read it, and what it should leave alone.
What you need before this chapter
This chapter assumes you have already done the following:
- Built a child component with a default slot and named slots, and filled them from a parent with the
slotattribute. - Used
@apiproperties and standard DOM events in a Lightning web component. - Seen that the parent owns slotted markup. The parent's CSS styles it, the parent's JavaScript handles its events, and the parent's data is bound to it.
The last point is the reason this chapter exists. The child renders the slot but does not own what goes into it, so the child needs specific tools to look at it.
Where slotted nodes live
Slotted elements are created by the parent's template. The child's template contains only the <slot> element, which is a placeholder. Because of this, the child's usual query method does not find slotted content.
| Call in the child | What it searches | Finds slotted content? |
|---|---|---|
| `this.template.querySelector(...)` | Elements written in the child's own template | No |
| `this.querySelector(...)` | Elements the parent passed into the child | Yes |
| `slot.assignedNodes()` | Nodes currently assigned to that slot | Yes, for that slot only |
| `slot.assignedElements()` | Element nodes currently assigned to that slot | Yes, for that slot only |
The two query methods search disjoint sets. this.template.querySelector never returns a slotted element, and this.querySelector never returns an element from the child's own template. If a query returns null and you are sure the element exists, check that you are using the method for the right owner.
import { LightningElement, api } from 'lwc';
export default class Dialog extends LightningElement {
@api
focusFirstField() {
// Searches parent-supplied content, not this component's template.
const field = this.querySelector('lightning-input, input, textarea, select');
if (field) {
field.focus();
}
}
}this.querySelector is a good fit when you need a specific element regardless of which slot holds it. The slot-based methods below are a better fit when you care about which slot the content is in.
Getting the slot element
To use assignedNodes() or assignedElements(), you first need the <slot> element. It belongs to the child's template, so this.template.querySelector finds it.
const footerSlot = this.template.querySelector('slot[name="footer"]');
const defaultSlot = this.template.querySelector('slot:not([name])');A named slot is selected with an attribute selector. The default slot has no name attribute, so slot:not([name]) selects it. A bare querySelector('slot') returns whichever slot appears first in the template, which is fragile if you later add another slot above it.
When the handler is attached to the slot with onslotchange, you do not need a query at all. The event's target is the slot.
Two ways to read assigned content
A slot gives you two read methods, and they return different things.
| Method | Returns | Includes text nodes? |
|---|---|---|
| `assignedNodes()` | All nodes assigned to the slot | Yes |
| `assignedElements()` | Only element nodes | No |
| `assignedNodes({ flatten: true })` | Assigned nodes, with nested slots and fallback content resolved | Yes |
Text is a node. If the parent writes this:
<c-card>
Plain text in the default slot
</c-card>then assignedNodes() on the default slot returns one text node, while assignedElements() returns an empty array. This difference matters when you count items. If you want "how many things did the parent give me", assignedElements() is usually the correct call. If you want "did the parent give me anything at all, including text", use assignedNodes().
The LWC compiler removes whitespace between tags in a template, so indentation in the parent's markup does not normally add empty text nodes. Do not rely on this for text you build at runtime, such as a text node created with document.createTextNode.
When to read: slotchange and the lifecycle
The child cannot read slot contents at any moment. Two points in the lifecycle matter.
connectedCallbackruns before the child's template has rendered. The<slot>element does not exist yet, sothis.template.querySelector('slot')returnsnull.renderedCallbackruns after the template has rendered. The slot exists and assigned nodes are available.
For content that changes while the component is on the page, use slotchange. This event fires on the <slot> element when its list of assigned nodes changes. It also fires once after the first assignment, so a single handler covers both the initial content and later updates.
Two properties of slotchange are easy to get wrong:
- It reports changes to the list of assigned nodes. Adding, removing, or replacing a direct child of the slot triggers it.
- It does not report changes inside those nodes. If the parent changes an attribute or text of a slotted element, no event fires.
- It bubbles but does not cross shadow boundaries, so a parent cannot listen for the child's
slotchangeon the child element.
Worked example: a checklist that counts its items
This component accepts any number of elements in its default slot. Each element carries a data-done attribute. The child reads those attributes and displays a summary.
<!-- checklist.html -->
<template>
<section class="checklist">
<h2>{summary}</h2>
<slot onslotchange={handleSlotChange}></slot>
</section>
</template>// checklist.js
import { LightningElement } from 'lwc';
export default class Checklist extends LightningElement {
total = 0;
done = 0;
handleSlotChange(event) {
const items = event.target.assignedElements();
this.total = items.length;
this.done = items.filter((item) => item.dataset.done === 'true').length;
}
get summary() {
return `${this.done} of ${this.total} done`;
}
}<!-- parent.html -->
<template>
<c-checklist>
<div data-done="true">Create account</div>
<div data-done="true">Verify email</div>
<div data-done="false">Add payment method</div>
</c-checklist>
</template>The first render shows "2 of 3 done". The handler runs because the slot received its initial nodes, and no connectedCallback or renderedCallback code is needed.
This example is read-only. The child inspects the parent's elements and stores the results in its own fields. It does not change the elements.
Fallback content and the flatten option
Fallback content is the markup inside a <slot> that shows when the parent provides nothing. It changes what the read methods return.
<!-- card.html (header section) -->
<header>
<slot name="header">Untitled</slot>
</header>// Inside a method of the card component, after it has rendered
const slot = this.template.querySelector('slot[name="header"]');
const assigned = slot.assignedNodes();
const flat = slot.assignedNodes({ flatten: true });If the parent supplies no header, the results are:
| Call | Result |
|---|---|
| `slot.assignedNodes()` | Empty array. Fallback content is not an assigned node. |
| `slot.assignedNodes({ flatten: true })` | The fallback text node containing "Untitled". |
Use the plain call to answer "did the parent supply content?" Use flatten: true to answer "what will the user see in this slot?" The flatten option also resolves slots that are nested through other components, which comes up when a slot is forwarded to a deeper child.
This is why the footer example from earlier in the tutorial works. The footer slot has no fallback content, and the handler checks assignedNodes().length > 0. Adding flatten: true there would be harmless, but adding fallback content to that slot and flattening would make the length check always true.
Reading versus changing
Reading slotted nodes is supported. Changing them is where problems start, because the parent owns them. Keep these rules in mind.
- Do not rewrite a slotted element's children or text. The parent's template manages that DOM. A manual edit can be overwritten on the next parent render, or it can break the parent's diffing.
- Do not add classes or inline styles to slotted elements. The parent's reactive bindings may reset them, and the parent has no way to know the child did it.
- Use public API on slotted components. If the slotted element is a custom LWC component, you can read only its
@apiproperties and call its@apimethods. Private fields are not accessible. - Do not store slotted nodes in reactive fields and expect them to track. An array of elements stored in a field goes stale when the parent replaces elements. Read from the slot again when you need the current list.
If the child needs to affect slotted content, give the parent a way to do it. Dispatch a custom event with the information, or accept a public property that the parent uses to adjust its own markup.
Edge cases
- Hidden slots. If the
<slot>element sits inside alwc:ifblock that is false, the slot is not rendered. It has no assigned nodes,querySelectorreturnsnull, and noslotchangefires. Check fornullbefore callingassignedNodes(). - Slots in iterations. A slot with the same name must not be repeated in a loop. Each name has one slot element in the template.
- Rerender loops. The handler writes to fields, and a field change causes a rerender. If the rerender caused another
slotchange, you would loop. A normal rerender does not change the assigned nodes, so a plain handler is safe. A handler that adds or removes slotted nodes can loop, which is another reason not to mutate them. - Unneeded writes. If the handler sets a field to the value it already holds, nothing meaningful happens, but if it builds a new array each time, the template receives a new object each time. Store counts and booleans where you can.
- Text-only content. A slot that holds only text returns an empty
assignedElements()array. If your logic depends on elements, handle the case where the parent passed text. - Timing in the parent. If the parent's slotted element appears after an asynchronous call, the child sees it through a later
slotchange. Do not poll.
Summary of the decision
- Need to react when content is added or removed? Use
onslotchangeon the slot and read inside the handler. - Need one specific slotted element, wherever it is? Use
this.querySelector. - Need the contents of one particular slot? Get the slot with
this.template.querySelector, then callassignedElements()orassignedNodes(). - Need to know what the user sees, including fallback content? Pass
{ flatten: true }. - Need the value of something that changes inside a slotted element? Have the parent pass it in through a property or an event, because
slotchangewill not tell you.
Exercise
A card component has <slot name="footer"></slot>. In connectedCallback, the developer runs this.template.querySelector('slot[name="footer"]').assignedNodes() and gets an error that says the result of the query is null. What is wrong, and where should the code run instead?
Show answer
In connectedCallback the child's template has not rendered yet, so the slot element does not exist and the query returns null. Move the read to an onslotchange handler on the slot (which also fires for the first assignment) or to renderedCallback, and check for null if the slot is inside a conditional block.
Exercise
A parent writes <c-checklist><div data-done="false">Task</div></c-checklist>. Later, a button in the parent changes the same element's data-done to "true". The checklist's summary still says "0 of 1 done". Why, and what are two ways to fix it?
Show answer
slotchange fires only when the list of assigned nodes changes. An attribute change on an existing element does not change that list, so the child's handler never runs. Fix it by making the parent pass the done state through a public property on the child (or remove and re-add the element, which is a poor choice), or by having the slotted element or parent dispatch a custom event that the child listens for and uses to recompute its counts.
Exercise
A header slot has fallback text "Untitled" and the parent supplies nothing. What do slot.assignedNodes() and slot.assignedNodes({ flatten: true }) return, and which one tells you whether the parent supplied content?
Show answer
assignedNodes() returns an empty array, and assignedNodes({ flatten: true }) returns the fallback text node. The first call tells you whether the parent supplied content. The flattened call tells you what is displayed.