If you're maintaining your Platform Developer I Certification, this Winter '25, you may have come across the concept of slot forwarding in Lightning Web Components (LWC).
Slot forwarding allows parent components to pass markup into predefined placeholder regions of a child component using the <slot>
element.
1. Default (Unnamed) Slot
An unnamed slot uses the <slot>
element as a placeholder for any markup that a parent component passes into the body of c-slot-demo
.
In the child component:
<!-- slotDemo.html -->
<template>
<h1>Add content to slot</h1>
<div>
<slot></slot>
</div>
</template>
In the parent component:
<!-- slotWrapper.html -->
<template>
<c-slot-demo>
<p>Content from parent</p>
</c-slot-demo>
</template>
Rendered output:
<h1>Add content to slot</h1>
<div>
<p>Content from parent</p>
</div>
2. Named Slots
Useful when you have multiple content areas to fill:
<!-- namedSlots.html -->
<template>
<p>First Name: <slot name="firstName">Default first name</slot></p>
<p>Last Name: <slot name="lastName">Default last name</slot></p>
<p>Description: <slot>Default description</slot></p>
</template>
Parent component:
<!-- slotsWrapper.html -->
<template>
<c-named-slots>
<span slot="firstName">Willy</span>
<span slot="lastName">Wonka</span>
<span>Chocolatier</span>
</c-named-slots>
</template>
3. Dynamic Slot Attributes
Slot name can be dynamic on the consumer side:
<template>
<c-item>
<span slot={dynamicName}></span>
</c-item>
</template>
4. Accessing Slotted Content
import { LightningElement } from 'lwc';
export default class NamedSlots extends LightningElement {
renderedCallback() {
const first = this.querySelector('span');
const all = this.querySelectorAll('span');
}
}
5. Conditional Rendering with Slots
<template>
<template lwc:if={expression}>
<div class="my-class">
<slot></slot>
</div>
</template>
<template lwc:else>
<slot></slot>
</template>
</template>
if:true
or if:false
for slot conditional rendering. Use lwc:if
and lwc:else
instead.
6. Slotchange Event
<!-- container.html -->
<template>
<slot onslotchange={handleSlotChange}></slot>
</template>
handleSlotChange(e) {
console.log('New slotted content added or removed!');
}
Summary
- Slots let you pass markup into components.
- Use unnamed slots for general content areas.
- Use named slots to target specific regions.
- Access slotted content with
this.querySelector
- Handle dynamic content with event -
slotchange
📚 Read more in the official Salesforce doc:
https://developer.salesforce.com/docs/platform/lwc/guide/create-components-slots.html
0 Comments