Blog>
Snippets

Fallback Content for Named Slots

Explains how to provide default content for named slots that displays only if no content is provided by the parent component.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Slot Fallback Content Example</title>
<style>
  .container {
    border: 1px solid #000;
    padding: 10px;
    margin-bottom: 10px;
  }
</style>
</head>
<body>

<custom-component>
  <div slot="header">Custom Header Content</div>
  <!-- No content for the 'footer' slot, so fallback content will show -->
</custom-component>

<template id="component-template">
  <div class="container">
    <slot name="header">Default Header Content</slot>
    <div>
      <!-- Main content goes here -->
    </div>
    <slot name="footer">Default Footer Content</slot>
  </div>
</template>

<script>
class CustomComponent extends HTMLElement {
  constructor() {
    super();
    const template = document.getElementById('component-template').content;
    const shadowRoot = this.attachShadow({ mode: 'open' });
    shadowRoot.appendChild(template.cloneNode(true));
  }
}

customElements.define('custom-component', CustomComponent);
</script>

</body>
</html>
This example demonstrates a Web Component with named slots. The CustomComponent class uses a shadow DOM to encapsulate its template. The template contains two named slots: 'header' and 'footer'. Default fallback content is provided inside the slots that will be displayed if no content is assigned to the respective slots by the parent component. In the usage of <custom-component>, only the 'header' slot is provided with content, while the 'footer' slot will display its fallback content.