Search code examples
javascripthtmllistviewweb-component

Is it possible to make a Web Component List with undetermined number of slot?


I know it can be achieved using Javascript by manually separate the slot elements and put them into the DOM tree but I wonder if it's supported within the box. Something like this:

<my-element>
    <div slot="items">Item 1</div>
    <div slot="items">Item 2</div>
    <div slot="items">...</div>
</my-element>

And the template should be like this:

<div class="items">
    <div class="item"> <!-- Should be 1 item per slot -->
        <p>Something else</p>
        <slot name="items"></slot>
    </div>
</div>

Is this only possible using slotchange and populate the items by Javascript? Is there any better solution, without Javascript or with less Javascript? Maybe there is an element similar to slot that I am not aware of?


Solution

  • since all slot="items" will be slotted into <slot name="items"> only with the slotchange Event can the Component Author determine what happened.

    Note: You do not populate the items, the default slotting mechanism does; you can only remove items after they are slotted; but then your HTML above needs more info on which Item needs to be slotted.

    Then the question remains, Why use multiple slot="items" at all then?? If a slot can take 1 item, then only assign 1 item

    Imperative Slots might help out: https://github.com/WICG/webcomponents/blob/gh-pages/proposals/Imperative-Shadow-DOM-Distribution-API.md

    Update, I misunderdstood OPs question

    All he needs to do is:

    Create another Web Component: <slotted-item slot="items"></slotted-item>