web-componentlit

Passing Web Component Slots to a Parent


I'm trying to get back into web components with lit and I'm having trouble with slots. I've made a sample button where I can add an icon to the start or end of the label with slot names like so:

<my-button type="submit">
  <span slot="button-icon-end">*</span>
  Yo im a button
</my-button>

And it will render out a button like Yo im a button * properly. However, I want to add more properties and customize that icon sometimes. I've tried making a second component to simply output exactly that span with the slot but it always put the * at the beginning.

@customElement('my-button-icon')
export class MyButtonIcon extends LitElement {
    override render() {
        return html`<span slot="button-icon-end">*</span>`
    }
}

Is there a way to bubble the slot up to a parent component with lit or even native web components?


Solution

  • I found a previous answer suggesting adding the attribute to the web component class directly. This works very nicely:

        override render() {
            this.slot = `button-icon-${this.position}`;
            return html`<span>*</span>`
        }