Sub topic 1
Why compose components with slots
A Lightning web component (LWC) rarely works alone. You build a page by nesting components, and each nesting decision raises a question: how does the outer component hand content to the inner one? This chapter explains why slots exist, what problem they solve, and how they differ from public properties. Later chapters cover the details of default slots, named slots, fallback content, ownership, and events.
Prerequisites
This chapter assumes you already know the following:
- The basic structure of a Lightning web component: an HTML template, a JavaScript class, and an optional CSS file, all in a folder with the same base name.
- How to use a child component in a parent template, for example
<c-card></c-card>. - How to expose a public property with
@api. - Basic HTML and DOM event handling, including
addEventListenerandon-prefixed handlers in templates.
You don't need any knowledge of slots. You don't need to know how shadow DOM works internally either. The few facts you need about it are explained below.
The composition problem
Suppose you build a card: a bordered box with a header area, a body, and a footer. The border, spacing, and layout are the same everywhere. What goes inside differs on every page.
Several ways exist to build this. The rest of this chapter compares two of them: configuring the child through public properties, and letting the parent supply markup through slots.
First attempt: public properties
The natural first step is to give the card public properties and render them. The child's template looks like this:
<!-- propCard.html -->
<template>
<article class="card">
<header>{heading}</header>
<div class="body">{bodyText}</div>
</article>
</template>// propCard.js
import { LightningElement, api } from 'lwc';
export default class PropCard extends LightningElement {
@api heading;
@api bodyText;
}The parent passes plain strings:
<!-- parent.html -->
<template>
<c-prop-card
heading="Order summary"
body-text="Two items in your cart.">
</c-prop-card>
</template>This works for text. Properties are explicit, easy to validate, and easy to document. For simple values, they are the right tool.
The approach breaks down when the content is not a string. Consider these requests, each of which is realistic:
- The header should contain an icon next to the title.
- The body should contain a form with three inputs.
- The footer should contain a
lightning-buttonwith a click handler. - One page needs a link in the body, and another needs a list.
With properties alone, you have two bad options. You can keep adding properties (headingIcon, showButton, buttonLabel, buttonVariant, and so on) until the card mirrors every component it might ever contain. Or you can pass HTML as a string. LWC does not render strings as markup, so that route does not work for components and event handlers. The card's API grows with every new use case, and the card has to know about things it was supposed to be independent of.
The slot approach
A slot is a placeholder in the child's template. The child decides where content goes and how that area is laid out. The parent decides what the content is. The child declares a slot with the <slot> element:
<!-- slotCard.html -->
<template>
<article class="card">
<header>
<slot name="header"></slot>
</header>
<div class="body">
<slot></slot>
</div>
</article>
</template>The component has no JavaScript logic to speak of, so the class is minimal:
// slotCard.js
import { LightningElement } from 'lwc';
export default class SlotCard extends LightningElement {}The parent writes markup between the opening and closing tags of <c-slot-card>:
<!-- parent.html -->
<template>
<c-slot-card>
<span slot="header">Order summary</span>
<p>Two items in your cart.</p>
<lightning-button label="Checkout" onclick={handleCheckout}></lightning-button>
</c-slot-card>
</template>Two rules are visible here:
- An element with a
slot="header"attribute goes into the slot namedheader. - Everything else goes into the unnamed slot, called the default slot.
The paragraph and the button have no slot attribute, so both appear in the card body. The card never needed to know that a button would be there. Adding a form, a list, or an image later requires no change to the card.
Notice also that onclick={handleCheckout} is written in the parent template and refers to a method on the parent's class. The card does not need an oncheckout event or a callback property for this. That point is part of ownership, covered later in this tutorial.
What a slot is, mechanically
The word "placeholder" is accurate, but it helps to be a little more precise, because several later behaviors follow from it.
When a component renders, the browser (or LWC's synthetic shadow DOM, where native shadow DOM is not in use) builds a tree for it. The child's template forms the child's shadow tree. The elements the parent wrote between the child's tags are not part of that shadow tree. They stay in the parent's tree, and the <slot> element tells the renderer where to display them. The word for this is assigning: the slot element has assigned nodes, and those nodes appear in the slot's position on screen.
The practical consequence is that slotted content is rendered inside the child's layout but created by the parent. The diagram shows the two sides.
This split gives the clearest way to remember what each side is responsible for.
| Concern | Child component | Parent component |
|---|---|---|
| Layout and structure around the content | Defines it | Does not control it |
| Which elements appear in a slot | Does not decide | Decides |
| Data bindings in slotted markup, such as `{orderTotal}` | Not involved | Evaluated against the parent's class |
| Event handlers on slotted elements | Not involved | Declared in the parent's template |
| Where the slot sits and what it is called | Decides | Must match the name |
Slots versus properties, in one comparison
Both mechanisms pass something from the parent to the child, but they pass different kinds of things.
| Row | Public property (`@api`) | Slot |
|---|---|---|
| What is passed | A value: string, number, object, array | Markup: elements and components |
| Who builds the markup | The child, from the value | The parent |
| How the child reacts to it | Directly, in JavaScript and template expressions | Indirectly, through the slot element and events like `slotchange` |
| Best for | Configuration and data | Structure and content |
| Cost of a new use case | A new property and template logic | Usually none |
A later chapter in this tutorial turns this into decision criteria, including cases where combining both is correct. For now, a rule of thumb is enough: if the child needs to compute with or validate the input, use a property. If the child only needs to display whatever the parent hands over, use a slot.
A well-designed component often uses both. A modal might take @api size as a property, because the modal's own CSS depends on it, and accept its title and buttons through slots, because the modal does not care what they contain.
Where slots appear in practice
You have probably already used slotted components without writing a slot. Base components in the lightning namespace use them. For example, lightning-card accepts a title attribute, which is a property. It also accepts content in slot="actions" and slot="footer", and the body goes into the default slot:
<template>
<lightning-card title="Account details" icon-name="standard:account">
<lightning-button
slot="actions"
label="Edit"
onclick={handleEdit}>
</lightning-button>
<p class="slds-p-horizontal_small">Name: {accountName}</p>
<p slot="footer">Last modified: {lastModified}</p>
</lightning-card>
</template>This is the property-and-slot pattern in a single component. The short, string-like value (title) is a property. The structural content (a button, paragraphs) goes through slots. Reading the documentation of base components with this distinction in mind makes their APIs easier to predict.
Things to expect before the later chapters
A few behaviors surprise developers new to slots. This section names them so they are not a surprise, and the later chapters of this tutorial cover each one in depth.
- Slotted content is optional. If the parent supplies nothing for a slot, the slot renders empty unless the child provides fallback content inside the
<slot>element. The child cannot assume a slot is populated. - Styling follows ownership. CSS in the child's
.cssfile styles the child's own template. Slotted elements belong to the parent, so the parent's stylesheet styles them. Writing a rule in the child and expecting it to restyle slotted content is a common mistake. - Queries follow ownership too. Inside the child,
this.template.querySelector()searches the child's own template, so it does not find slotted elements. The child reads slotted content through the slot element'sassignedNodes()method, or throughthis.querySelector(), which looks at the host element's own children. The appropriate choice is covered in the chapter on accessing slotted content. - The
slotattribute goes on a direct child. The attribute only has an effect on elements written directly inside the child component's tags. Nesting the element one level deeper inside a wrapperdivsends the wrapper, not the element, to the slot. - Slots are not reactive properties. The child does not get a field that updates when slotted content changes. To respond to changes, it listens for the
slotchangeevent.
A short decision walk-through
Walk through a new component design with these questions, in order.
- Is the thing being passed a plain value the child must read in JavaScript? If yes, use an
@apiproperty. - Is it markup, such as elements, components, or user-defined layout? If yes, use a slot.
- Does the surrounding layout stay the same while the content varies? If yes, the layout belongs in the child and the content arrives by slot.
- Does the child need to branch on whether content exists? A slot can still work. The child listens for
slotchangeand checks the assigned nodes. If the check becomes complicated, consider a boolean property instead.
Here is a combined example that applies these answers. The panel takes its visual variant as a property, because its CSS depends on it. Its content arrives through slots:
<!-- infoPanel.html -->
<template>
<section class={panelClass}>
<h2 class="title">
<slot name="title">Details</slot>
</h2>
<slot></slot>
</section>
</template>// infoPanel.js
import { LightningElement, api } from 'lwc';
export default class InfoPanel extends LightningElement {
@api variant = 'plain';
get panelClass() {
return `panel panel_${this.variant}`;
}
}<!-- usage.html -->
<template>
<c-info-panel variant="warning">
<span slot="title">Payment overdue</span>
<p>Your invoice was due on 1 November.</p>
</c-info-panel>
</template>The text "Details" inside the title slot is fallback content. It displays only when the parent supplies no slot="title" element. Here the parent supplies one, so "Payment overdue" replaces it.
Summary of the model
A component that only accepts properties controls its own output completely, but it can only show what its properties can describe. A component with slots gives up control over the content in exchange for flexibility. It keeps control of layout. The parent builds the content in its own template, with its own data and event handlers, and the child places that content where its slots are. Everything in the following chapters adds detail to that division of responsibility.
Exercise
A teammate has built c-alert with the properties message, iconName, buttonLabel, and showButton. Requests keep arriving to put a link, a second button, or a formatted list inside the alert. Explain why properties are a poor fit for these requests, and describe how you would restructure c-alert so that it needs no changes for new content. Keep one property that still belongs on the component.
Show answer
Properties pass values, so each new kind of content needs a new property and new template logic, and the alert has to know about the content it displays. LWC also does not render markup passed as a string, so a link or a list cannot be sent through message. Restructure the alert so that its template defines only the layout and exposes slots, for example a default slot for the body and a named actions slot for buttons. The parent then writes the link, buttons, or list directly between the <c-alert> tags, with its own data bindings and click handlers. A property such as variant (for example info or error) should stay, because the alert's own CSS depends on its value.
Exercise
In the following parent template, which elements end up in the default slot of c-slot-card, and which end up in the header slot?
<c-slot-card>
<div>
<span slot="header">Title</span>
</div>
<p>Body text</p>
</c-slot-card>
Show answer
The div and the p both go to the default slot. The slot="header" attribute only takes effect on an element written directly inside the child component's tags. The span is nested inside the div, so it travels with the div into the default slot, and the header slot stays empty. To fix it, remove the wrapper div or put slot="header" on the div itself.