liveBook · Manning

Slot element

As explained in Web Components in Action

The HTML slot element defines a placeholder in a component's shadow tree for user-provided or assigned content.

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

How Web Components in Action covers it

How deep it goes
Explains named and unnamed slots, fallback content, and Shadow DOM setup, while deferring in-depth Shadow DOM treatment.
Examples
Demonstrates business-card fields, named placeholders, fallback values, and a generic unnamed slot.
What it assumes
Assumes HTML templating familiarity, teaches slot syntax directly, and introduces only the Shadow DOM setup needed to use it.
What you can do after
Build Web Components that accept named or generic content through Shadow DOM slots with useful fallback text.
How it connects
Connects slots with Shadow DOM, templates, Web Components, and the DOM.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Components in Action. The section links point to the parts of the book it draws on.