Sub topic 3
Slots for Composing Lightning Web Components
Assume you know basic LWC templates, child components, @api, and DOM events. This chapter compares slots with public properties and shows how to observe slotted content.
Slots or public properties?
A public property passes data to a child. A slot passes markup. Use a property when the child controls the structure:
<c-badge label="Ready"></c-badge>Use a slot when the parent needs to supply flexible content while the child controls its position and layout:
<c-card>
<span slot="header">Order summary</span>
<p>Two items in your cart.</p>
</c-card>| Choose a public property when... | Choose a slot when... |
|---|---|
| The input is data or a simple value. | The input is custom markup. |
| The child owns the complete rendering. | The parent needs control over content. |
Detecting content changes with `slotchange`
A slotchange event fires when the nodes assigned to a slot change. It does not fire for every change inside an already-assigned element.
<slot name="footer" onslotchange={handleFooterChange}></slot>handleFooterChange(event) {
this.hasFooter = event.target.assignedNodes().length > 0;
}The child can use this state to hide an empty footer or change its layout.
Reading slotted nodes from the child
assignedNodes() returns the nodes currently placed in a slot. The child can inspect them, but the parent still owns those nodes. Avoid changing their internal structure from the child.
handleFooterChange(event) {
const nodes = event.target.assignedNodes();
this.hasFooter = nodes.some((node) => node.nodeType === Node.ELEMENT_NODE);
}Passing slots through nested components
A wrapper can expose a slot and place that slot inside another component. The wrapper forwards the parent’s content:
<!-- wrapper.html -->
<template>
<c-card>
<slot name="header" slot="header"></slot>
<slot></slot>
</c-card>
</template>The slot attribute chooses the destination slot on c-card. Without it, the forwarded content goes to the child’s default slot.
Pitfalls and best practices
- Match
slot="name"with<slot name="name">exactly. - Do not use a property and a slot for the same responsibility without documenting precedence.
- Put fallback text inside the slot for useful empty states.
- Style the child’s layout in the child, but style slotted markup where that markup is declared.
- Do not assume
slotchangedetects descendant text or attribute changes. - Use
assignedNodes()after the component renders, usually from a slot event.
Exercise
Should a child use a public property or a slot to receive a configurable button with custom label and markup?
Show answer
Use a slot because the parent is supplying markup. Use a public property when the child should create the button from simple data.