How does component composition work using slots in Lightning Web Components?
Answer
Basics: Properties pass data; slots pass markup. A c-card component can define a place for a body and a header, and each parent decides what to put there. This is composition: reusable wrappers (cards, modals, layouts, error boundaries) with parent-supplied content.
How it works:
- Child template:
<slot></slot>defines the unnamed default slot;<slot name="header"></slot>defines a named slot. - Parent usage: any content inside
<c-card>goes to the default slot; elements withslot="header"go to the named slot. - Fallback content placed inside
<slot>appears only when the parent provides nothing. - The child can listen to
slotchangeto react when the assigned content changes. - The projected content belongs to the parent: its events, data bindings and CSS scope are the parent's.
Advanced / deep dive: Slotted content is created and owned by the parent, so the parent's styles apply to it, not the child's, and the parent's event handlers fire in the parent's context. The child can inspect slotted nodes through the slot element (assignedElements()) or this.querySelector for light-tree children, but should not depend on their implementation. A named slot can receive multiple elements; one element can fill only one slot. In synthetic shadow, a few details of slot behavior and ::slotted styling differ from native shadow, so verify visually. Scoped slots (letting a child pass data back to slotted markup) exist via lwc:slot-data; check current release notes for availability and status. With light DOM components, slots behave differently (they use light DOM slotting and cannot use fallback in the same way), so check the documentation when using . Slots combine well with for boundary wrappers and with for conditional regions.