Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Web Components - Multiple elements per slot

I'm working on new web-components and ran into some issues concerning slots.

I have an outer container-component with a "main-slot" inside, in which multiple elements should be inserted (into the same slot). However, it is only possible to add one element per named slot.

My question: is there a way to add multiple elements to one named slot? Like shown here:

<own-container>
   <own-element slot="main"></own-element>
   <own-element slot="main"></own-element>
   <own-element slot="main"></own-element>
   <own-element slot="main"></own-element>
</own-container>
like image 742
Fabio Düll Avatar asked Oct 23 '25 22:10

Fabio Düll


1 Answers

There is also imperative <slot>

super().attachShadow({
        mode: 'open',
        slotAssignment: 'manual' // imperative assign only
      })

But! you get Named slots OR Imperative slots, on one Web Component

To mimic named <slot>, assigning content to the same named <slot>
you probably need the Mutation Observer API

addendum

You can have multiple elements per slot:

<component-with-slots>
    <H1 slot="title">Web Components are great!</H1>
    <h2 slot="title">A bit hard to master</h2>
    <b slot="title">But Great!</b>
</component-with-slots>

<script>
  customElements.define('component-with-slots', class extends HTMLElement {
    constructor() { 
        super()
          .attachShadow({mode:'open'})
          .innerHTML = `<slot name="title"></slot>`; 
    }
  });
</script>
like image 104
Danny '365CSI' Engelman Avatar answered Oct 26 '25 11:10

Danny '365CSI' Engelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!