1

How do I pass data to a slotted element in Lit?

I’ve tried…

<my-component>
  <slot .mydata=“${this.mydata}”> <\slot>
<\my-component>

But doesn’t seem to work, is programmatically the only way to do this?

hegsie
  • 93
  • 1
  • 7
  • Could you provide a minimal repro using the https://lit.dev/playground or elaborate on the use case? A [slot](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/slot) is an element where children get projected. One way to set the `mydata` property on all slotted children is to listen to the [`slotchange`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLSlotElement/slotchange_event) event and then update the property programmatically. – YouCodeThings Jul 26 '22 at 18:31
  • I’m not sure that’s possible, I’m using the Vaadin Router with nested routes and want to pass data from the first level down to the nested level which uses the slot element – hegsie Aug 01 '22 at 09:36

1 Answers1

0

We use slot on parent element.
Default (unnmamed) slot

<div class="parent>
  <slot></slot>
</div>

Named slot

<div class="parent>
      <slot name="slot-name"></slot>
    </div>

Then insert html tag inside parent by using slot.

<main-parent>
<div slot="slot-name"></div>
</main-parent>

For default slot,you don't need to add slot attribute.

Note: Slot is used to insert external html inside parent element.
If you don't need to insert html, you don't need to use slot.

For pass data from parent to child.

<next-child childattr=${this.mydata} ></next-child>

For pass from child parent. You need to dispatch custom event with bubbles:true

Anil kumar
  • 1,216
  • 4
  • 12