Sub topic 13
Composing components with slots
Slots let a parent component pass markup into a child component. The child decides where that markup appears. This chapter covers default slots, named slots, fallback content, the slotchange event, and who owns and styles slotted content. It assumes you know the earlier chapters: the component bundle, @api properties, and shadow DOM encapsulation.
Why slots exist
@api properties pass data into a child. They work poorly for passing markup. Suppose you build a card with a header, a body, and a footer. If the card exposes one property per region, every caller must squeeze HTML into strings or build a new child component for each case.
The web platform has the <slot> element for this. A slot is a placeholder inside a component's shadow tree. When the component is used, the browser renders the host element's children at the slot's position. The card controls the layout, and the caller controls the content.
LWC uses this standard element directly. The template compiler passes <slot> through, and the LWC engine supplies the matching behavior when it runs in synthetic shadow mode.
The default slot
A <slot> with no name is the default slot. It receives every child of the host that is not assigned to a named slot.
<!-- simplePanel.html -->
<template>
<section class="panel">
<slot></slot>
</section>
</template><!-- parent.html -->
<template>
<c-simple-panel>
<p>This paragraph is rendered inside the panel's slot.</p>
</c-simple-panel>
</template>The <p> is written in the parent's template, so the parent owns it. It appears visually inside the child's <section>.
Named slots
A component can define several slots by giving each one a name. The caller picks a slot by setting the slot attribute on a direct child of the host element.
<!-- cardPanel.html -->
<template>
<article class="card">
<header class="card-header">
<slot name="header">Untitled</slot>
</header>
<div class="card-body">
<slot></slot>
</div>
<footer class="card-footer">
<slot name="footer"></slot>
</footer>
</article>
</template><!-- orderSummary.html -->
<template>
<c-card-panel>
<h2 slot="header">Order 1042</h2>
<p>Two items, shipping to Dublin.</p>
<button slot="footer" onclick={handleConfirm}>Confirm</button>
</c-card-panel>
</template>The <h2> goes to the header slot and the <button> goes to the footer slot. The <p> has no slot attribute, so it goes to the default slot.
The diagram below shows how the host's children are distributed.
Fallback content
Content placed between <slot> and </slot> in the child is fallback content. It renders only when nothing is assigned to that slot. In cardPanel.html, the header slot shows "Untitled" if the caller supplies no slot="header" element.
Fallback content belongs to the child. Use it for sensible defaults, not for required content.
Rules to remember
- Only direct children of the host can be assigned to a named slot. A
slot="header"attribute on a grandchild has no effect. - Several elements can share one slot name. They appear in source order.
- Elements with no
slotattribute go to the default slot. If the child has no default slot, those elements are not displayed. - The
slotattribute is plain HTML. It is not an LWC directive.
Ownership of slotted content
Slotted elements are created and owned by the parent that wrote them, not by the child that displays them. This has three practical consequences.
- Event handlers on slotted elements, such as
onclick={handleConfirm}above, run methods on the parent's class. The child never sees them. - Slotted elements are not in the child's shadow tree.
this.template.querySelector('p')insidecardPaneldoes not find the paragraph. The child can reach slotted elements withthis.querySelector(), which searches the host's light DOM children. - Reactive updates to slotted content come from the parent's fields. When
orderSummarychanges a field used in its slotted markup, the parent re-renders that markup, and the child does nothing.
Reacting to slot changes: slotchange
A child sometimes needs to know whether a slot has content, for example to hide an empty footer. The <slot> element dispatches a standard slotchange event when its assigned nodes change. Attach the handler in the template with onslotchange, then read the nodes with assignedNodes().
<!-- cardPanel.html -->
<template>
<article class="card">
<header class="card-header">
<slot name="header">Untitled</slot>
</header>
<div class="card-body">
<slot></slot>
</div>
<footer class={footerClass}>
<slot name="footer" onslotchange={handleFooterChange}></slot>
</footer>
</article>
</template>// cardPanel.js
import { LightningElement } from 'lwc';
export default class CardPanel extends LightningElement {
hasFooter = false;
get footerClass() {
return this.hasFooter ? 'card-footer' : 'card-footer card-footer-empty';
}
handleFooterChange(event) {
const slot = event.target;
this.hasFooter = slot.assignedNodes().length > 0;
}
}slotchange fires after the first render when content is already present, and again whenever nodes are added to or removed from the slot. The event does not fire when a slotted node's own contents change. The handler above therefore only tracks whether the slot is populated.
Styling slotted content
Style scoping follows ownership. CSS in cardPanel.css applies to elements in the card's own template, such as .card-header. It does not reach the parent's slotted <h2>. To style slotted elements, put the rules in the parent's CSS file, because the parent owns them.
The standard ::slotted() pseudo-element exists for styling slotted nodes from inside a shadow tree. It depends on native shadow DOM. LWC's synthetic shadow mode does not support it, so avoid it in components that must run on the Salesforce platform.
A child can still style the slot's wrapper. The div.card-body around the default slot is part of the child's template, so the child can add padding, borders, or layout rules to it.
Slots versus @api properties
| Need | Use |
|---|---|
| Pass a string, number, or object | `@api` property |
| Pass markup the caller controls | Slot |
| Let the caller supply a default-able region | Named slot with fallback content |
| Send data back to the parent | `CustomEvent` |
| Pass a function to render each item | Not possible with slots alone, so use a child component with `@api` properties |
Slots are one-way: markup flows down into the child. The child cannot send data back into slotted content, so slots do not replace properties and events. They complement them.
Common errors
- Putting
slot="x"on a nested element instead of a direct child of the host. - Defining two slots with the same name and expecting content to appear in both. Only the first matching slot gets it.
- Querying slotted content with
this.template.querySelector, which returnsnull. Usethis.querySelector. - Expecting
slotchangeto fire on every internal change of a slotted node. - Using
::slotted()in a component that will run under synthetic shadow.
Exercise
A component c-alert-box has the template <template><div class="box"><slot name="title">Notice</slot><slot></slot></div></template>. A parent writes <c-alert-box><p>Disk is full.</p></c-alert-box>. What does the user see, and who owns the <p>?
Show answer
The user sees "Notice" (the fallback content of the title slot, since nothing is assigned to it), followed by "Disk is full." in the default slot. The parent owns the <p>. The parent's CSS and handlers apply to it, and alertBox.js can only reach it with this.querySelector('p'), not this.template.querySelector('p').
Exercise
In cardPanel, you want to add the CSS class card-footer-empty only when no element is assigned to the footer slot. Which event and which slot method do you use, and why must the handler track state in a class field?
Show answer
Listen for slotchange on the footer slot with onslotchange, then call assignedNodes() (or assignedElements()) on event.target and check the length. The result goes into a class field such as hasFooter because reassigning a field is what triggers a re-render, so the footerClass getter is re-evaluated with the new value.