Sub topic 9
Passing slots through nested components
This chapter assumes you can write a child component with a default slot, named slots, and fallback content. You should also know that the parent owns the markup it puts into those slots. You can write a slotchange handler and call assignedNodes().
Real components rarely sit in a flat two-level tree. A page contains a panel, and the panel contains a card. This chapter covers how content written in the page reaches a slot in the card, what the panel in between has to do, and which behaviors change along the way.
The nesting problem
Suppose c-card from the earlier chapters has a header, a default, and a footer slot. You build c-product-panel, which uses c-card internally and adds product-specific behavior. A page then uses c-product-panel.
The page author wants to write this:
<!-- order-page.html -->
<template>
<c-product-panel>
<span slot="title">Order summary</span>
<p>Two items in your cart.</p>
<lightning-button slot="actions" label="Checkout" onclick={handleCheckout}></lightning-button>
</c-product-panel>
</template>The slot attribute only matches a slot in the template of the component you put the element in. Here that component is c-product-panel, so slot="title" must match a <slot name="title"> in the panel's template. The card is invisible to the page. If the panel's template doesn't declare slots named title and actions, the span and the button are never rendered. The default-slot paragraph is also dropped unless the panel declares a default slot.
You have two options.
- Collapse the layers. Make the page use
c-carddirectly. This is simplest, but the page then loses whatever the panel adds. - Forward the slots. The panel declares its own slots and passes them into the card's slots. This is slot forwarding.
Forwarding a slot
A <slot> element can itself be given a slot attribute. The name attribute says which slot this element is. The slot attribute says which slot of the child component it is placed into. Used together, they relay content.
<!-- product-panel.html -->
<template>
<c-card>
<slot name="title" slot="header">Untitled order</slot>
<p class="note">Prices include tax.</p>
<slot></slot>
<slot name="actions" slot="footer"></slot>
</c-card>
</template>Reading it from top to bottom:
<slot name="title" slot="header">is a slot calledtitleon the panel's public surface. Whatever the page puts inslot="title"is placed into the card'sheaderslot.<p class="note">is markup the panel owns. It has noslotattribute, so it goes to the card's default slot.<slot></slot>is the panel's default slot. It has noslotattribute either, so it also goes to the card's default slot, after the note.<slot name="actions" slot="footer">is a slot calledactionson the panel, forwarded to the card'sfooter.
The panel can rename slots while forwarding. The page sees title and actions, which fit the product domain. The card keeps its generic header and footer. The panel owns that translation, and the card can change its slot names without breaking pages, as long as the panel is updated.
Two rules from the template compiler apply here.
- A slot element must be a direct child of the component tag it is being slotted into.
<c-card><div><slot name="actions" slot="footer"></slot></div></c-card>doesn't forward anything to the footer, because the slot is no longer a direct child ofc-card. - Slot names in
nameandslotare static strings. You can't compute them from a property.
Who owns what when slots are forwarded
Forwarding adds a layer, but it doesn't change ownership. The markup that ends up in the card's header, body, and footer comes from two components.
| Content | Written in | Owner | Styled by | Event handlers and data bindings live in |
|---|---|---|---|---|
| `<span slot="title">` | `order-page.html` | `order-page` | `order-page` CSS | `order-page.js` |
| `<p>Two items...</p>` | `order-page.html` | `order-page` | `order-page` CSS | `order-page.js` |
| `<lightning-button>` | `order-page.html` | `order-page` | `order-page` CSS | `order-page.js` (`handleCheckout`) |
| `<p class="note">` | `product-panel.html` | `product-panel` | `product-panel` CSS | `product-panel.js` |
| The `<slot>` elements | `product-panel.html` | `product-panel` | Not styled themselves | Not applicable |
Three consequences follow.
- The panel's CSS doesn't style the page's button. Both the panel and the card can't reach into content that the page wrote. To style it, the page uses its own CSS file, or the panel and card expose styling hooks such as CSS custom properties.
- The
onclickon the button runshandleCheckoutinorder-page.js. The panel and the card don't need to know the button exists. A click event does bubble up through the DOM and out of both components. A listener onc-cardinside the panel's template would see it, so be deliberate about where you attach listeners. - A
<slot>element is a placeholder, not content. You can't apply a class to it and expect the page's content to get that class. If the panel wants to wrap the forwarded content in a styled container, it needs a real element, such as a<div>inside the card's default slot, around the<slot>.
Fallback content across layers
Fallback content is shown when a slot has nothing assigned to it. Forwarding changes what "nothing" means.
The card declares <slot name="header">Untitled</slot>. In the panel, <slot name="title" slot="header"></slot> is always assigned to that card slot, because the panel's template always contains it. From the card's point of view the header slot is never empty, so the card's Untitled fallback never appears, even when the page passes no title.
The fix is to put fallback content on the forwarding slot:
<slot name="title" slot="header">Untitled order</slot>When the page supplies a title, the page's content is shown. When it doesn't, the panel's fallback is shown, rendered inside the card's header. The card's own Untitled text is now unreachable through this panel. This is usually what you want, because the panel is the more specific component and should choose its own default.
The forwarding slots in the earlier example for default and actions have no fallback. When the page provides nothing, they render nothing, but the card still counts them as assigned content. That matters for the next section.
Detecting content with slotchange and assignedNodes
The card from the earlier chapter hides its footer when the parent supplies no footer content:
// card.js (original version)
import { LightningElement } from 'lwc';
export default class Card extends LightningElement {
hasFooter = false;
handleFooterChange(event) {
const slot = event.target;
this.hasFooter = slot.assignedNodes().length > 0;
}
get footerClass() {
return this.hasFooter ? 'footer' : 'footer slds-hide';
}
}Behind the panel, this code has a bug. The card's footer slot always has exactly one assigned node: the panel's <slot name="actions"> element. So assignedNodes().length is always 1, and the footer is shown even when the page supplied no actions. You get an empty footer bar.
assignedNodes() returns the nodes directly assigned to that slot, and a forwarding <slot> element is one such node. To see through it, pass { flatten: true }. With that option, any assigned <slot> is replaced by its own assigned nodes, recursively. If a forwarded slot has no content and no fallback, it contributes nothing.
| Call on the card's footer slot | Page supplies a button | Page supplies nothing |
|---|---|---|
| `assignedNodes()` | `[<slot name="actions">]` | `[<slot name="actions">]` |
| `assignedNodes({ flatten: true })` | `[<lightning-button>]` | `[]` |
| `assignedElements({ flatten: true })` | `[<lightning-button>]` | `[]` |
There is a second issue with event.target. The slotchange event bubbles. When the page adds a button, the panel's actions slot fires slotchange. Because that slot is itself assigned to the card's footer slot, the event continues to the card's footer slot, and your onslotchange listener on the card runs. In that case event.target can be the panel's slot, not the card's. Reading event.currentTarget always gives the element the listener is attached to.
This version works with and without forwarding:
// card.js (works directly and behind forwarding slots)
import { LightningElement } from 'lwc';
export default class Card extends LightningElement {
hasFooter = false;
handleFooterChange(event) {
const slot = event.currentTarget;
this.hasFooter = slot.assignedNodes({ flatten: true }).length > 0;
}
get footerClass() {
return this.hasFooter ? 'footer' : 'footer slds-hide';
}
}<!-- card.html (footer section, unchanged) -->
<footer class={footerClass}>
<slot name="footer" onslotchange={handleFooterChange}></slot>
</footer>A component that sits in the middle, such as the panel, reads its own slots with plain assignedNodes(). The nodes assigned to the panel's actions slot are the page's elements directly. Use flatten: true when you are the inner component, because you can't know how many layers sit above you.
Whitespace matters when you test for content. A text node containing only whitespace counts as an assigned node on a default slot, so a page that writes the component tag across several lines can make .length > 0 true. If you care, filter with assignedElements({ flatten: true }), which returns element nodes only.
Choosing where a decision belongs
Forwarding is not free. Each forwarding layer repeats slot names and has to be updated when the inner component changes. Use this checklist.
- Does the wrapper add real value? If it only passes slots through, have the page use
c-carddirectly. - Is the content structural? Markup that the page writes, such as a title, a body, or actions, fits slots. Plain values, such as a string title with no formatting, fit a public property on the wrapper that it passes to the card.
- Should the page know about the card? If the panel hides the card as an implementation detail, forward slots with the panel's own names. If the card is part of the contract, expose it differently.
- Do you need many slots? More than four or five forwarded slots suggests that the wrapper has become a thin copy of the card. Consider whether the wrapper should extend a shared base template instead.
You can also mix both techniques. The panel can take a title property for simple text and a title slot for rich content. It then renders the slot with the property as fallback:
<!-- product-panel.html (mixed approach) -->
<template>
<c-card>
<slot name="title" slot="header">{title}</slot>
<slot></slot>
<slot name="actions" slot="footer"></slot>
</c-card>
</template>// product-panel.js
import { LightningElement, api } from 'lwc';
export default class ProductPanel extends LightningElement {
@api title = 'Untitled order';
}The page can now write either <c-product-panel title="Order summary"> or provide a slot="title" element when it needs an icon or a link in the heading. The slot wins when both are present.
Common mistakes with forwarded slots
- Forgetting that fallback content belongs to the forwarding slot. The inner component's fallback text never shows. Put your fallback on the outermost forwarding slot.
- Counting assigned nodes without
flatten. Any "is there content?" check in an inner component gives a false positive behind a forwarding slot. - Using
event.targetinslotchangehandlers. The event bubbles through forwarded slots, soevent.targetmay be a slot in another component. Useevent.currentTargetor query your own slot fromthis.template. - Wrapping a forwarding slot in another element. The
slotattribute only works on a direct child of the component tag. - Expecting wrapper CSS to style forwarded content. Only the component that wrote the markup can style it. Provide custom properties for shared theming.
- Querying across layers. The card can't use
this.querySelectorto find the page's button, and the panel can't usethis.template.querySelectorto find it either. Content owned by the page is queried from the page. Inner components should react toslotchangeandassignedNodes(), and should communicate with events or public methods.
Summary
A slot is matched against the template of the component that the markup is written inside, so the page can't reach the card through the panel. The panel declares its own slots and forwards them with <slot name="x" slot="y">, and it can rename them on the way. Ownership doesn't change: the page's content is still styled and handled by the page. What does change is the shape of the slots the inner component sees. A forwarding slot is always an assigned node, so fallback content must go on the forwarding slot, and content checks must use assignedNodes({ flatten: true }) read from event.currentTarget.
Exercise
The card from this chapter has <slot name="footer"></slot> with no fallback, and the panel forwards it with <slot name="actions" slot="footer"></slot>. A page uses the panel and passes no actions. The card's handler uses slot.assignedNodes().length > 0. What does hasFooter become, why, and what single change fixes it?
Show answer
hasFooter becomes true, so an empty footer shows. The card's footer slot has one assigned node, the panel's <slot name="actions"> element, even though that slot has no content. Passing { flatten: true }, as in slot.assignedNodes({ flatten: true }), replaces the forwarding slot with its own assigned nodes, which are none. The length is then 0 and hasFooter is false.
Exercise
A page uses <c-product-panel> and provides no slot="title" element. The card has <slot name="header">Untitled</slot>. The panel has <slot name="title" slot="header">Untitled order</slot>. Which text is displayed in the header? What would be displayed if the panel's slot had no text inside it?
Show answer
"Untitled order" is displayed. The forwarding slot is an assigned node of the card's header slot, so the card's own fallback never renders. The panel's slot has nothing assigned from the page, so its fallback is rendered inside the card's header. If the panel's slot had no text, the header would be empty, because the card's "Untitled" fallback is still not used.
Exercise
A teammate writes <c-card><div class="actions-wrap"><slot name="actions" slot="footer"></slot></div></c-card> in the panel's template. The page's button doesn't appear in the card's footer. Why, and how do you keep a styled wrapper?
Show answer
The slot attribute only takes effect on a direct child of the component tag, and here the <slot> is inside a <div>. The <div> itself has no slot attribute, so it goes to the card's default slot. To keep the wrapper, put the <div slot="footer" class="actions-wrap"> as the direct child of c-card, and put <slot name="actions"></slot> inside it.