Sub topic 1
Why Compose Components with Slots
Prerequisites
This chapter assumes you know the basic Lightning web component structure, how a parent uses a child component, public properties with @api, and basic HTML and DOM events.
Why Compose Components with Slots
A slot is a placeholder in a child component's template. The child controls the layout, while the parent supplies markup for part of that layout. This creates composition: you reuse the same component structure with different content.
Slots are useful when the supplied content can contain markup, such as links, buttons, or formatted text. A public property is usually better for data, such as a title string or an item count.
The Default Slot
A default slot is unnamed. Content in the parent without a slot attribute goes into it.
<!-- card.html -->
<template>
<article class="card">
<h2><slot name="header">Untitled</slot></h2>
<div class="body">
<slot></slot>
</div>
</article>
</template>The second <slot> is the default slot. The header slot also shows fallback content, which is displayed when the parent supplies no header.
Named Slots
A named slot gives the parent control over a specific location. The parent assigns content with a matching slot attribute.
<!-- parent.html -->
<template>
<c-card>
<span slot="header">Order summary</span>
<p>Two items are in your cart.</p>
</c-card>
</template>The <span> fills the child’s header slot. The paragraph fills the default slot. The child still owns the overall layout, so the parent does not need to know how the card arranges its sections.
Exercise
Which slot receives the paragraph in the example, and why?
Show answer
The default slot receives it because the paragraph has no slot attribute.