Sub topic 5
Who Owns Slotted Content: Styling, Data, and Events
This chapter assumes you can build a basic Lightning web component (HTML template, JavaScript class, CSS file), use a child component in a parent template, and mark properties with @api. It also assumes you know the default slot, named slots, and fallback content from the earlier chapters. Here the question is narrower: once markup has been slotted into a child, which component is responsible for it?
The ownership rule
A component owns the markup written in its own template. Markup you write between the tags of a child component, such as a <span slot="header">, belongs to the component whose template contains it. That is the parent.
The child decides where the content appears. The parent still owns the content. Four things follow from this:
- The parent's CSS styles the slotted content.
- Expressions such as
{itemCount}in slotted markup read the parent's properties. - Event handlers on slotted elements are the parent's methods, and
thisinside them is the parent. - The parent's
this.template.querySelector()finds the slotted elements. The child's does not.
The browser still renders slotted content inside the child's layout. Ownership and rendered position are separate ideas.
A running example
The example reuses the card from earlier in this tutorial and adds a parent that binds data, styles the slotted content, and handles events. First, the child. It has a click listener on the footer container, and its CSS has a rule that targets .title.
<!-- card.html -->
<template>
<article class="card">
<header>
<slot name="header">Untitled</slot>
</header>
<div class="body">
<slot></slot>
</div>
<footer class="footer" onclick={handleFooterClick}>
<slot name="footer"></slot>
</footer>
</article>
</template>/* card.css */
.body {
padding: 1rem;
}
/* Matches only elements in card.html that have class="title".
It does not touch the parent's slotted span. */
.title {
color: red;
}// card.js
import { LightningElement } from 'lwc';
export default class Card extends LightningElement {
handleFooterClick(event) {
console.log('Card saw a click from', event.target.tagName);
}
}Now the parent. It owns all the slotted markup, so it supplies the data, the styles, and the handlers.
<!-- orderSummary.html -->
<template>
<c-card onclick={handleCardClick}>
<span slot="header" class="title">Order summary</span>
<p class="count">{itemCount} items in your cart.</p>
<lightning-button
slot="footer"
label="Checkout"
onclick={handleCheckout}
></lightning-button>
</c-card>
</template>// orderSummary.js
import { LightningElement } from 'lwc';
export default class OrderSummary extends LightningElement {
itemCount = 2;
handleCheckout() {
console.log('Checkout handler runs in', this.constructor.name);
}
handleCardClick(event) {
console.log('Parent saw a click on the card host from', event.target.tagName);
}
}/* orderSummary.css */
.title {
font-weight: bold;
color: #032d60;
}
.count {
color: #444444;
}The sections below explain what each file does and why.
Styling slotted content
The parent's CSS applies
The span with class="title" is in the parent's template, so the parent's stylesheet styles it. It renders bold and dark blue. The child's .title { color: red; } rule has no effect on it, even though the span is displayed inside the child's <header>.
Style scoping in Lightning Web Components works per component. A component's CSS applies to the elements in its own template. It does not reach into other components' templates, and other components' CSS does not reach into it. Slotted content stays in the parent's scope.
What the child can and cannot do
The child cannot restyle slotted content with ordinary selectors. It has three options.
- Style the wrapper. The child styles its own elements, such as
.body,.footer, and the<header>. Padding, borders, backgrounds, and layout on those wrappers affect where and how the slotted content sits. - Rely on inheritance. Inherited properties such as
color,font-family, andfont-sizeflow from the child's wrapper elements into slotted content. For example,colorset on.bodyis inherited by the slotted<p>unless the parent sets its owncolor. In the example above, the parent's.countrule wins. - Expose styling hooks. CSS custom properties (
--card-accent: ...) also inherit into slotted content. A parent can set them on the slotted element or onc-card, and a stylesheet can read them withvar(). This is the supported way to let a child offer theming.
The ::slotted() pseudo-element lets a child's CSS target elements assigned to a slot. It takes a simple selector and matches only the slotted elements themselves, not their descendants. Check that it behaves as you expect in your target environment before relying on it, because the platform emulates shadow DOM in some contexts.
Data binding
Template expressions inside slotted markup are evaluated against the parent. In the example, {itemCount} reads OrderSummary.itemCount. The child has no access to it.
Two consequences:
- Reactivity belongs to the parent. When
itemCountchanges, the parent re-renders and the paragraph updates. The child needs no code for this and may not even re-render. - The child cannot supply variables to slotted markup. LWC has no scoped slots. The slotted content cannot write
{row.name}whererowcomes from the child. If the child owns the data (a list renderer, for example), pass it through a public property, an event, or a child component the parent configures. Do not try to make the slotted markup read it.
The child can still read the slotted nodes, but it reads them as DOM. It cannot read the parent's data behind them. Use slot.assignedNodes() or this.querySelector(), covered in a later chapter.
Events
Handlers belong to the parent
The onclick={handleCheckout} on the slotted lightning-button binds to the parent's method. When the user clicks Checkout, handleCheckout runs with this set to the OrderSummary instance. The child's code is not involved in that call.
Events travel through the child's DOM
Slotted content sits inside the child's layout, so bubbling events pass through the child's elements on their way up. A click on the Checkout button follows this path:
- The button's own
onclickhandler (the parent'shandleCheckout). - The
slotelement inside the child's<footer>. - The child's
<footer>, whereonclick={handleFooterClick}listens. - The
c-cardhost element in the parent's template, whereonclick={handleCardClick}listens.
This surprises people in two ways.
- The child can observe events from content it did not write.
handleFooterClickincard.jslogs a click that came from a button the parent supplied. A child that listens on a wrapper around a slot receives bubbling events from any content placed in it. This is useful for delegation, such as a toolbar that reacts to any button click. It is a problem if the child assumes it only sees its own elements. event.targetdepends on where the listener is. For a slotted element, the target in the child's listener is the slotted element itself, because the parent's tree is outside the child's. A listener onc-cardin the parent seesc-cardas the target for events that originate inside the child's own template. Events that originate in the slotted button still report the button.
Stopping and redirecting events
If the parent does not want the child's footer listener to see a click, it calls event.stopPropagation() in its handler. The child can likewise stop an event from reaching the parent. Do this sparingly, because other listeners higher up may depend on the event.
Child-to-parent events are separate
The slotted content's events are the parent's own business. When the child wants to tell the parent something, it dispatches a CustomEvent from its own template or host, and the parent listens on c-card:
// inside card.js
handleClose() {
this.dispatchEvent(new CustomEvent('close'));
}<!-- in the parent's template -->
<c-card onclose={handleClose}></c-card>Do not use a slotted element's events as a messaging channel from the child to the parent. The child cannot add listeners to the parent's handlers, and it should not depend on the parent attaching them.
Querying slotted content
Ownership decides which query method finds the slotted elements.
| Call | Where it runs | Finds slotted `.count` paragraph? |
|---|---|---|
| `this.template.querySelector('.count')` | Parent (`OrderSummary`) | Yes. The parent owns it. |
| `this.template.querySelector('.count')` | Child (`Card`) | No. It searches only the child's own template. |
| `this.querySelector('.count')` | Child (`Card`) | Yes. It returns elements passed into the child's slots. |
| `this.template.querySelector('slot[name="footer"]')` | Child (`Card`) | Returns the slot element. It does not return the slotted nodes. |
The child can call this.querySelector('[slot="footer"]') after rendering and get the button the parent provided. From there it can call an @api method on a slotted custom component. Use this sparingly. It couples the child to a particular piece of the parent's content, and the parent can change or omit that content.
Tracing a failure back to ownership
Most slot bugs at this level come from assuming the wrong owner. A short checklist:
| Symptom | Likely cause | Fix |
|---|---|---|
| Child CSS rule has no effect on content in a slot | The content belongs to the parent's scope | Style it in the parent, use a styling hook, or style the child's wrapper |
| `{value}` in slotted markup is empty | The expression resolves against the parent, and the property is on the child | Define the property in the parent, or pass the data another way |
| Child's `this.template.querySelector` returns `null` for slotted element | The child's template does not contain the node | Use `this.querySelector`, or `slot.assignedNodes()` |
| A child listener fires for clicks the child did not expect | Events bubble through the slot | Check `event.target`, or stop propagation in the parent |
| Handler's `this` has no child methods | The handler is the parent's method | Move the logic to the parent, or dispatch a `CustomEvent` the child can handle |
Design guidance from ownership
Ownership gives you a few rules for deciding what the child and parent each do.
- Layout is the child's job. Spacing, borders, and positioning of slot regions belong in the child's CSS. Colors and typography for slotted content belong in the parent's.
- Content and its logic go together in the parent. If the content needs data, formatting, or handlers, keep them in the parent's template and class. The child needs only a slot.
- Make the child tolerate any content. Wrapper listeners should check
event.targetbefore acting. Layout rules should not assume a particular tag. - Promote a shared need to an
@apicontract. If the child must read or control something in the slotted content, define a public property, method, or event. Do not reach into the parent's markup.
Exercise
In the example, the child's card.css contains .title { color: red; } and the parent's orderSummary.css contains .title { font-weight: bold; color: #032d60; }. The parent's span has class="title" and is slotted into the card's header. What color does the text render in, and why? Then name two ways the card could still influence the color without editing orderSummary.css.
Show answer
It renders dark blue (#032d60). The span is in the parent's template, so only the parent's stylesheet applies to it. The child's .title rule matches only elements in the child's own template. The card can influence the color by setting an inherited property such as color on a wrapper (only if the parent has not set its own, which this parent has). A better way is to expose a styling hook, for example color: var(--card-title-color, #032d60) in a rule the parent writes. The card can also offer a documented ::slotted() rule if the target environment supports it.
Exercise
A user clicks the Checkout button in the example. List, in order, which handlers run and which component owns each method. What does event.target.tagName log in handleFooterClick?
Show answer
First handleCheckout runs, owned by the parent (OrderSummary). The click then bubbles through the slot to the footer, where handleFooterClick runs, owned by the child (Card). It then bubbles to the c-card host, where handleCardClick runs, owned by the parent. Because the button is outside the child's shadow tree, the target is not retargeted, so handleFooterClick logs the tag name of the slotted element, LIGHTNING-BUTTON.
Exercise
The child Card wants to read the paragraph the parent slotted into the default slot. Which of this.template.querySelector('p') and this.querySelector('p') works, and why? Which component's property does {itemCount} in that paragraph refer to?
Show answer
this.querySelector('p') works. It returns elements passed into the child's slots. this.template.querySelector('p') searches only the child's own template and returns null for slotted content. {itemCount} refers to the parent's property, because slotted markup is evaluated in the parent's context.