Combining Named and Anonymous Slots
Gives an example of a component that uses both named and anonymous slots, showing how to structure the template for different use cases.
<style>
.component {
border: 1px solid #000;
padding: 16px;
margin-bottom: 8px;
}
</style>
<template id="my-component">
<div class="component">
<slot name="header"></slot>
<slot></slot> <!-- Anonymous slot for default content -->
<slot name="footer"></slot>
</div>
</template>
<script>
class MyComponent extends HTMLElement {
constructor() {
super();
const template = document.getElementById('my-component').content;
const shadowRoot = this.attachShadow({ mode: 'open' }).appendChild(template.cloneNode(true));
}
}
customElements.define('my-component', MyComponent);
</script>
<!-- Usage of the component -->
<my-component>
<div slot="header">Header Content</div>
<div>Default Content</div>
<div slot="footer">Footer Content</div>
</my-component>
This CSS styles a simple component with a border, padding, and margin. The HTML template defines a custom element 'my-component' with a named slot for the header, an anonymous slot for the default content, and a named slot for the footer. The JavaScript registers the 'my-component' element using the Web Components API. The usage example shows how to provide content for the named slots and the default (anonymous) slot.