The <slot> element marks a placeholder in a component’s Shadow DOM, letting user-provided content replace template values without adding queryable <span> wrappers. section 7.4 section 7.5
Use slots in two closely related ways:
- Give a slot a name, such as <slot name="email">, then provide matching content with slot="email". section 7.5
- Leave a slot unnamed when one generic content position is enough; direct child content fills it automatically. section 7.5
- Keep fallback text inside the slot; missing named content displays that fallback instead of producing an error. section 7.5
Named business-card fields
A template can define <slot name="firstname">First</slot> and <slot name="website">http://website.com</slot>. The component then supplies <span slot="firstname">Ben</span> and <span slot="website">...</span>. Before this works, attach a shadow root with attachShadow({mode: 'open'}) and place the component’s content inside it. section 7.5
Listing 7.14. Placing slot tags in our template to allow content replacement
<div class="biz-card">
<div class="logo"></div>
<div class="top-text">
<h1><slot name="firstname">First</slot>
<slot name="lastname">LastName</slot></h1> #1
<h3>
<slot name="title">Job Title</slot> #2
</h3>
</div>
<div class="bottom-text">
<h3>phone:
<slot name="phone">#xxx.xxx.xxxx</slot> #3
</h3>
<h3><slot name="email">email@email.com</slot> /
<slot name="website">http://website.com</slot></h3> #4
</div>
</div>
Inspect the complete template showing named slots for names, job title, phone, email, and website, including fallback values. section 7.5
