tlitookilakin
tlitookilakin

Reputation: 61

How do I assign a custom element's text contents to a template slot?

I'm creating some web components and would like to insert the contained text into a template slot. I'd like to make it slottable as opposed to simply copying their value so the browser can naturally handle changes to the text instead of having to pass it through the component itself.

According to MDN textNodes are slottable, however I can't find any real means of doing this aside from the deprecated element from v1. (textNodes do not support attributes, so I can't simply assign it a slot that way, and .assignedSlot() is read-only.) Support outside the documentation is pretty minimal, although this is to be expected from such a new technology.

<my-element>some text</my-element>

<template>
 <h3><slot name="label"></slot></h3>
 <p>Derp</p>
</template>

Using this as a simplified example, I'd like some text to appear in the label slot, and get updated accordingly when the markup changes. Is there a good/integrated way to do this? Will I have to resort to a mutationObserver?

Upvotes: 6

Views: 596

Answers (1)

Supersharp
Supersharp

Reputation: 31171

You cannot assign a text node via a named <slot> simply because a named slot require to match an element with a slot attribute.

As a consequence, you'll need to embed your text in a element at least:

<my-element>
    <span slot="label">some text</span>
</my-element>

Alternatly, an unnamed <slot> can match all the light DOM content, including text nodes.

Upvotes: 3

Related Questions