Sub topic 8
Reading slotted nodes from the child
This chapter assumes you can build a child component with default and named slots, and that you know who owns slotted content (the parent). You should also be comfortable with @api properties and DOM events. Here you will learn how the child can look at what the parent put in its slots.
Slotted content lives outside the child's template
The parent's template creates slotted elements, so the parent owns them. The child's this.template covers only the child's own markup, so this.template.querySelector() does not return slotted elements.
The child has two ways to read slotted content:
this.querySelector()andthis.querySelectorAll()return elements the parent passed into any of the child's slots.slot.assignedNodes()andslot.assignedElements()return what is currently assigned to one specific slot.
Querying from the host
Use this.querySelector() when you want a particular element, such as the first input, wherever it sits among the slots.
import { LightningElement, api } from 'lwc';
export default class FormPanel extends LightningElement {
@api focusFirstField() {
const first = this.querySelector('lightning-input');
if (first) {
first.focus();
}
}
}The call returns null when the parent supplied no matching element, so always check the result. It also matches only the elements the parent passed in. It does not look inside the shadow tree of those elements.
Asking a slot what it holds
When you care about a specific slot, ask that slot. The slot element exposes the DOM methods below.
| Method | Returns | Includes text nodes |
|---|---|---|
| `assignedNodes()` | Nodes assigned to the slot | Yes |
| `assignedElements()` | Elements assigned to the slot | No |
| `assignedNodes({ flatten: true })` | Assigned nodes, or the slot's fallback content if nothing is assigned | Yes |
Whitespace between tags in the parent's markup can produce text nodes, so assignedNodes() may return more than you expect. Use assignedElements() when you count items.
Fallback content is not an assigned node. For an empty slot with fallback, assignedNodes() returns an empty array, which is why the footer example in the previous chapter can treat a length of zero as "the parent supplied nothing".
Example: counting items in a slot
This panel shows how many elements the parent placed in its default slot. It also exposes a method that focuses the first input.
<!-- itemPanel.html -->
<template>
<p class="count">{countLabel}</p>
<div class="items">
<slot onslotchange={handleSlotChange}></slot>
</div>
</template>// itemPanel.js
import { LightningElement, api } from 'lwc';
export default class ItemPanel extends LightningElement {
count = 0;
get countLabel() {
return `${this.count} item(s)`;
}
handleSlotChange(event) {
const slot = event.target;
this.count = slot.assignedElements().length;
}
@api focusFirst() {
const first = this.querySelector('lightning-input');
if (first) {
first.focus();
}
}
}<!-- parent.html -->
<template>
<c-item-panel>
<lightning-input label="Name"></lightning-input>
<lightning-input label="City"></lightning-input>
</c-item-panel>
</template>The browser fires slotchange when the slot is first populated and again whenever the assigned nodes change. The handler therefore sets the initial count as well as later updates.
Timing
Slotted content may not be available early in the child's life.
- In
connectedCallback, the child has not rendered, sothis.querySelector()andassignedElements()can return nothing. Do not read slotted content there. slotchangeis the dependable signal for slot content. Read the nodes inside that handler.renderedCallbackruns after each render, so it can read slotted content. Guard any work you do there so it does not repeat on every render.
Reading versus changing
Reading is safe. Modifying is not. Slotted elements belong to the parent, and the parent's template re-renders them. If the child changes their attributes, children, or styles directly, the parent's next render can overwrite the change, and the two components become tightly coupled.
When the child needs to influence slotted content, give the parent a way to do it. Expose an @api property or method on the child, or dispatch a custom event, and let the parent decide what to change. You may call public @api methods on a slotted component, such as focus() in the example above, because that is the contract the slotted component publishes.
Exercise
A card component uses this.template.querySelector('lightning-button') to find a button the parent placed in its footer slot, and it always gets null. Give the cause and two ways to fix it.
Show answer
The button is owned by the parent, so it is not part of the card's own template and this.template.querySelector() cannot see it. Fix 1: use this.querySelector('lightning-button'). Fix 2: attach onslotchange to the footer slot and call event.target.assignedElements() to get the button. Either approach returns null or an empty array if the parent supplied no button, so check for that.
Exercise
In an empty slot that has fallback text, what does assignedNodes() return, and what changes with { flatten: true }?
Show answer
Plain assignedNodes() returns an empty array, because fallback content is not assigned to the slot. With { flatten: true }, it returns the slot's fallback nodes when nothing is assigned.