Sub topic 12
When a slot is a better fit than a property
This chapter assumes you can already expose a child property with @api, set it from a parent template, and render a child component. It covers one more way to give a child something to show: a slot. It also gives you rules for choosing between a property, a slot, a method, and an event.
The problem with properties for markup
A public property carries data. A string, a number, an object, and an array all fit. Suppose the child is a card, and the parent wants to put a button, an icon, or a formatted paragraph inside it. You could try to describe that markup with properties:
// Fragile: the child has to know every kind of content the parent might want.
@api headerText;
@api headerIconName;
@api showFooterButton;
@api footerButtonLabel;Every new variation needs another property, and the child template fills up with lwc:if blocks. The parent also cannot put arbitrary markup inside the child, such as a link with its own click handler.
A slot reverses this. The child declares a place where content goes. The parent decides what the content is.
How a slot works
A slot is a placeholder in the child's template, written as <slot></slot>. Whatever the parent places between the child's opening and closing tags is rendered at that spot.
<!-- infoCard.html (child) -->
<template>
<article class="card">
<header>
<slot name="header"></slot>
</header>
<div class="body">
<slot></slot>
</div>
<footer class={footerClass}>
<slot name="footer" onslotchange={handleFooterChange}></slot>
</footer>
</article>
</template>This template has three slots:
<slot name="header">is a named slot. It receives only elements that carryslot="header".<slot></slot>is the default (unnamed) slot. It receives everything that has noslotattribute.<slot name="footer">is a second named slot. It also listens forslotchange, which a later section explains.
// infoCard.js (child)
import { LightningElement } from 'lwc';
export default class InfoCard extends LightningElement {
hasFooter = false;
get footerClass() {
return this.hasFooter ? 'footer' : 'footer slds-hide';
}
handleFooterChange(event) {
this.hasFooter = event.target.assignedNodes().length > 0;
}
}The parent supplies the content:
<!-- taskBoard.html (parent) -->
<template>
<c-info-card>
<h3 slot="header">Release checklist</h3>
<p>Review the open items before Friday.</p>
<ul>
<template for:each={items} for:item="item">
<li key={item.id}>{item.label}</li>
</template>
</ul>
<lightning-button slot="footer" label="Mark all done" onclick={handleDone}>
</lightning-button>
</c-info-card>
</template>The <h3> goes into the header slot, because it has slot="header". The paragraph and list have no slot attribute, so they go into the default slot. The button goes into the footer slot.
The child never declares an @api property for any of this. The parent's {items} binding and the handleDone handler both belong to the parent's class. When items changes, the parent re-renders its own markup, and the child is not involved.
Who owns slotted content
The parent owns slotted content, not the child. This has practical effects:
- The parent's JavaScript controls the content. Bindings such as
{item.label}and handlers such asonclick={handleDone}resolve against the parent's class. - The parent's template, not the child's, is where you use
this.template.querySelectorto reach slotted elements. The child reaches them withthis.querySelector, which returns elements passed into its slots. It does not find them withthis.template.querySelector. - Events from slotted elements fire in the parent's context. The child does not need a handler for them.
The consequence is that the child controls the layout and the parent controls the content, and neither needs to know the details of the other.
Fallback content
Anything you put inside a <slot> element in the child is fallback content. The browser renders it only when the parent supplies nothing for that slot.
<!-- emptyState.html (child) -->
<template>
<div class="empty">
<slot>
<p>Nothing to show yet.</p>
</slot>
</div>
</template>If the parent writes <c-empty-state></c-empty-state> with no content, the child shows "Nothing to show yet." If the parent writes <c-empty-state><p>No tasks match your filter.</p></c-empty-state>, the parent's paragraph replaces the fallback.
Fallback content is a good way to give a child a sensible default without a @api property to switch it on.
Detecting whether a slot has content
Sometimes the child needs to know whether the parent filled a slot. The earlier InfoCard example hides an empty footer wrapper so it does not leave an empty bar. The slotchange event supports this. It fires when the nodes assigned to a slot change, including once when the slot is first populated. Calling assignedNodes() on the slot element, which is event.target, returns those nodes.
Notice that the example hides the footer with a CSS class, not with lwc:if. If you wrapped the <slot> itself in lwc:if={hasFooter}, the slot would not render until hasFooter was true. A slot that is not rendered never fires slotchange, so hasFooter would stay false forever. Keep the slot in the DOM and hide its wrapper.
Choosing between a property, a slot, a method, and an event
Start with what the parent wants to give or ask for.
| The parent wants to... | Use | Why |
|---|---|---|
| Give the child a value to display or a setting to apply | Public property (`@api`) | The child decides how to render a value. The parent only supplies data. |
| Give the child a block of markup, possibly with its own handlers | Slot | The parent writes the markup. The child only provides a place for it. |
| Tell the child to do something now, such as focus or reset | Public method (`@api` method) | An action is not a value, and a property would need a change to trigger it. |
| Receive a result or notification from the child | Custom event | Data flows up through events. The child does not modify what it receives. |
A few rules of thumb help when two options both seem to fit:
- If the content is a string or a number and the child formats it, use a property. For example,
heading="Release checklist"is simpler than a header slot if the child always renders an<h3>. - If the parent needs control over the element type, its attributes, or its event handlers, use a slot.
- If the child must transform or validate the input, use a property with a setter. A slot gives the child no hook for changing what the parent wrote.
- If you find yourself adding a
showXboolean and anxLabelstring for each optional region, replace them with a slot.
Slots and properties also combine well. A card can take @api variant to choose its color scheme and offer slots for its content. The property governs the child's own behavior, and the slots hold the parent's content.
Gotchas
- Slots are not data transport. The child cannot read a value out of slotted markup the way it reads a property. It can see the assigned nodes, but treating them as input makes the component hard to test and to reuse.
- Slot names are fixed in markup. The
nameon<slot>and theslotattribute on the parent's element must match exactly, including case. A typo does not raise an error. The content simply falls into the default slot, or renders nowhere if no default slot exists. - Content with no matching slot is dropped. If the child has no default slot and the parent puts unlabeled content inside it, that content does not appear.
- Styling crosses the boundary one way. Slotted content is styled by the parent's CSS. The child's own stylesheet does not reach into it, so the child cannot reliably restyle what the parent provides.
- The parent still re-renders its own content. A reactive change to
itemsupdates the slotted list without the child doing anything. If you expected the child to need a refresh, you probably do not.
Exercise
A c-alert-box child currently has @api message, @api showAction, and @api actionLabel. The product team now wants some alerts to include a link with a custom click handler, and others to include a bulleted list. Which approach fits better, and what does the child template need?
Show answer
Use slots. The parent needs to control the markup and its handlers, which properties cannot express without adding more and more @api fields. The child template should have a default <slot> for the message body, and optionally a named <slot name="action"> for the link or button. The parent then writes the content between <c-alert-box> and </c-alert-box>, with slot="action" on the element that belongs in the action area. The showAction and actionLabel properties can be removed. If the child wants to hide an empty action area, it can use an onslotchange handler that toggles a CSS class, not lwc:if around the slot.
Exercise
A child has <template lwc:if={hasFooter}><slot name="footer" onslotchange={handleFooterChange}></slot></template>, and handleFooterChange is what sets hasFooter. The footer never appears even though the parent supplies it. Why?
Show answer
hasFooter starts as false, so the slot is not rendered. A slot that is not rendered never fires slotchange, so the handler never runs and hasFooter never becomes true. The fix is to always render the slot and hide its wrapper element with a CSS class that depends on hasFooter.