Sub topic 6
Slots or Public Properties?
Prerequisites
This chapter assumes you already know the following:
- How to build a Lightning web component with an HTML template, a JavaScript class, and a CSS file.
- How to use a child component in a parent template.
- How to declare a public property with
@api. - How the default slot, named slots, and fallback content work, as covered in the earlier chapters.
The question behind the choice
A child component often has a part that changes from one use to the next. You can let the parent supply that part in two ways:
- A public property. The parent passes a value, and the child decides how to render it.
- A slot. The parent passes markup, and the child decides where to put it.
Both work for many cases, so it is easy to pick one by habit. The better question is who should control the final markup. With a property, the child controls it. With a slot, the parent does.
What each mechanism gives you
Properties: the child keeps control
When the parent sets @api message, the child receives a value and writes the HTML around it. That has several consequences:
- The child can validate or normalize the value in a setter or getter.
- The child can compute derived state from it, such as a CSS class or an
aria-label. - The markup stays consistent in every place the component is used.
- The value can come from anywhere, including Apex results, the record page, or a flow.
- Tests are simple, because you assign a property and check the output.
The cost is rigidity. A string property cannot carry a link, a bold word, or a button. If you want that, you add more properties (linkUrl, linkLabel, iconName, and so on). The API grows each time someone needs another variation.
Slots: the parent keeps control
When the parent passes markup into a slot, the parent owns that markup. Its styles, data bindings, and event handlers all belong to the parent. The child only chooses where the content appears. That brings these benefits:
- The parent can pass any markup, including other components.
- The child's API stays small, because it needs no property for each variation.
- Handlers in the parent can react to clicks on slotted buttons without custom events.
The cost is less control in the child. The child cannot validate what arrives and cannot easily react to what is inside. It also cannot guarantee consistent markup, because each parent writes its own.
A worked comparison
Start with a message box that uses only properties.
<!-- messageBox.html -->
<template>
<div class={boxClass} role="status">
<p>{message}</p>
</div>
</template>// messageBox.js
import { LightningElement, api } from 'lwc';
export default class MessageBox extends LightningElement {
@api variant = 'info';
@api message = '';
get boxClass() {
return `box box-${this.variant}`;
}
}<!-- parent.html -->
<template>
<c-message-box
variant="warning"
message="Your trial ends in 3 days.">
</c-message-box>
</template>This is a good design while the message is plain text. The child validates nothing but does control the markup. Now a product owner asks for an "Upgrade now" link inside the message. Using properties, you add linkUrl and linkLabel. A week later someone wants a bold word, and then a button instead of a link. Each request changes the component's API.
With a slot, the message box never has to change:
<!-- messageBox.html -->
<template>
<div class={boxClass} role="status">
<slot>No message</slot>
</div>
</template><!-- parent.html -->
<template>
<c-message-box variant="warning">
Your trial ends in <strong>3 days</strong>.
<a href="/upgrade">Upgrade now</a>
</c-message-box>
</template>The variant property stays, because the variant is a simple choice that the child turns into a CSS class. The message becomes a slot, because it is free-form markup. That split, small controlled values as properties and open-ended content as slots, is the pattern to remember.
Combining both
Many good components use both. The Lightning Design System components in the base library work this way. For example, lightning-card has title and icon-name properties, plus title, actions, and footer slots.
Here is a panel with a heading property, a default slot for the body, and a named slot for actions:
<!-- panel.html -->
<template>
<section class="panel">
<h2 class="panel-heading">{heading}</h2>
<div class="panel-actions">
<slot name="actions"></slot>
</div>
<div class="panel-body">
<slot></slot>
</div>
</section>
</template>// panel.js
import { LightningElement, api } from 'lwc';
export default class Panel extends LightningElement {
@api heading = '';
}<!-- parent.html -->
<template>
<c-panel heading="Open cases">
<lightning-button
slot="actions"
label="New case"
onclick={handleNewCase}>
</lightning-button>
<p>You have {caseCount} open cases.</p>
</c-panel>
</template>The heading is short text that the child places inside an <h2>. Because the child controls it, every panel in the app has the same heading level. The button and paragraph are parent content. The handleNewCase handler and the caseCount value both live in the parent's class, and the panel never sees them.
Decision criteria
Ask these questions in order. The first clear answer usually settles it.
- Is the varying part data or markup? Data, such as a string, number, boolean, or list of records, points to a property. Markup, such as links, buttons, icons, or other components, points to a slot.
- Does the child need to act on the value? If the child computes a class, validates, sorts, formats, or counts, use a property. The child can't easily do these things with slotted markup.
- Must the markup be identical everywhere? If you need a fixed heading level or fixed accessibility attributes, use a property. A slot lets each parent write its own markup.
- Will admins or flows configure it? Lightning App Builder and Flow Builder expose
@apiproperties declared in the component's metadata. They cannot fill a slot. A component that admins need to configure must use properties for those parts. - Would you otherwise add many near-duplicate properties? If so, switch that part to a slot.
Comparison table
| Concern | Public property | Slot |
|---|---|---|
| What the parent passes | A value (string, number, object, array) | Markup, including components |
| Who writes the final markup | The child | The parent |
| Who owns handlers and bindings | The child, with custom events to notify the parent | The parent |
| Validation in the child | Easy, in a setter or getter | Hard, needs `assignedNodes()` |
| Visible in App Builder or Flow | Yes, if exposed in metadata | No |
| API growth as variations appear | Grows with each variation | Stays small |
| Consistency across usages | High | Depends on each parent |
| Reacting to changes | Setter runs on every new value | `slotchange` fires only when assigned nodes change |
Edge cases
Rich text through a property
A common shortcut is to pass an HTML string through a property and inject it with innerHTML. This skips the template's escaping, so it can open the component to cross-site scripting if the string includes user input. Lightning Web Security and Locker also restrict some of these patterns. If a parent needs to pass links or formatting, use a slot. The template then renders each element normally.
Slot content changes do not call setters
When the parent changes a property, the child's setter runs, and you can react. Slotted content works differently. If the parent updates text inside a slotted <span>, the child is not told. The slotchange event fires only when the set of assigned nodes changes, for example when an element is added, removed, or moved into the slot. If the child must react to data changes, the parent should pass that data as a property too.
Lists
A list of items is almost always better as a property. Consider a component that shows five rows, each with a label and a value. With an items array, the child loops with for:each and renders every row the same way. With slots, the parent must write each row, and the child cannot sort or filter them.
// statList.js
import { LightningElement, api } from 'lwc';
export default class StatList extends LightningElement {
@api items = [];
get sortedItems() {
return [...this.items].sort((a, b) => a.label.localeCompare(b.label));
}
}<!-- statList.html -->
<template>
<ul>
<template for:each={sortedItems} for:item="item">
<li key={item.id}>{item.label}: {item.value}</li>
</template>
</ul>
</template>Sorting here is only possible because the child receives data. Nothing in a slot lets you do that without reading and rearranging DOM nodes.
Mixing both for the same part
Avoid offering a property and a slot that fill the same spot, such as a message property and a default slot that both render in the same place. Parents will not know which wins. The exception is fallback content: a slot's fallback can show a property's value when the slot is empty. This is a clean way to give a short form and a rich form of the same part.
<!-- panel.html (heading section) -->
<h2 class="panel-heading">
<slot name="heading">{heading}</slot>
</h2>A parent that sets only heading="Open cases" gets plain text. A parent that supplies <span slot="heading">Open <em>urgent</em> cases</span> replaces it. The child still decides that the wrapper is an <h2>.
Testing
Components that use properties are easy to test in Jest. You create the element, assign the property, append it to the document, and check the shadow DOM. For slots, you also create child elements, set their slot attribute, and append them to the host before you check the result. Both are manageable, but slot tests are longer. That is a minor reason to prefer properties for simple values.
Common mistakes
- Using slots for every part. A component made entirely of slots is an empty layout that every parent must fill. Use properties for values the child can render well.
- Adding a property for every variation. If you have
linkLabel,linkUrl,linkTarget, andshowIconon one component, a slot is probably a better fit. - Expecting the child to style slotted content. Slotted content belongs to the parent, so the child's CSS file does not reach it. If the appearance must be controlled, use a property such as
variantthat the child turns into a class on its own wrapper. - Expecting App Builder to configure a slot. Admins cannot fill a slot. Expose a property if that part must be configurable.
- Relying on
slotchangefor data updates. It tracks assigned nodes, not their contents.
Summary of the rule
Use a property when the child should decide how a value looks. Use a slot when the parent should decide what goes there. Use both when there is a short, controlled form and an open-ended form of the same part. Whichever you choose, keep the child's API as small as the real variations allow.
Exercise
A c-status-badge component currently has label, iconName, linkUrl, and linkLabel properties. Product asks for a badge that contains a bold word and a button. Which change is the better design, and which part of the API should stay a property?
Show answer
Replace the free-form content (the label text, link, and any extra markup) with a default slot, since the requests keep adding markup variations. Keep short controlled values that the child turns into styling or structure, such as a variant property that becomes a CSS class. The linkUrl and linkLabel properties can be removed because the parent can now write its own link.
Exercise
A parent updates the text inside a <span slot="footer"> element that it passed to a child. Does the child's slotchange handler run? What should the parent do if the child needs to know about the new text?
Show answer
No. slotchange fires only when the nodes assigned to the slot change (added, removed, or moved), not when the contents of an existing assigned node change. If the child needs to react to the text, the parent should also pass the value as a public property, so the child's setter runs.
Exercise
Admins need to set the heading of a custom card in Lightning App Builder, and developers also want to place a button in the card's header area. How would you design the component?
Show answer
Expose heading as an @api property and declare it in the component's metadata so App Builder can set it. Add a named slot such as actions for the button, because markup and components can only be passed through slots. Optionally use the heading property as fallback content inside a heading slot, so developers can override it with richer markup.