0

element

import { LitElement, html } from 'lit-element';

class Component extends LitElement {
  render () {
    return html`
      <slot name="activator">
        <button @click="${this.openDialog}">Default Button</button>
      </slot>

      <custom-dialog></custom-dialog>
    `;
  }

  openDialog () {
    // code to open dialog
  }
}

customElements.define('custom-dialog', Component);

index.html

<head>
  <script type="module" src="src/custom-dialog.js"></script>
</head>
<body>
  <custom-dialog>
    <button slot="activator">Outside Button</button>
  </custom-dialog>
</body>

Given the custom component above and my implementation on a simple html page. You'll notice that I'm using a slot button.

How do I call the openDialog() method using the slot button?

I checked docs for events but I found nothing relevant to this.

Thanks in advance.

Justin Fagnani
  • 10,483
  • 2
  • 27
  • 37
jofftiquez
  • 7,548
  • 10
  • 67
  • 121

1 Answers1

2

You need a click event listener on the slot or some ancestor of the slot:

Try moving the @click binding to the slot element itself. click events bubble, so this will handle both the default slot content button and the slotted button from the light DOM. This might not work in ShadyDOM, so you may want to put the event listened on a wrapper element around the slot.

import { LitElement, html } from 'lit-element';

class Component extends LitElement {
  render () {
    return html`
      <slot name="activator" @click="${this.openDialog}">
        <button>Default Button</button>
      </slot>

      <custom-dialog></custom-dialog>
    `;
  }

  openDialog () {
    // code to open dialog
  }
}

customElements.define('custom-dialog', Component);
Justin Fagnani
  • 10,483
  • 2
  • 27
  • 37
  • "Try moving the @click binding to the slot element itself". Wow this makes much more sense than adding an event to the slot node when the @slotchange event was fired. That's what I was doing so far. Another solution is jquery way `document.getElementById('foo').openDialog()` lol – jofftiquez Feb 28 '20 at 07:50
  • @Justin Fagnani what if there are two buttons in same slot, how to differentiate which one called it? – minigeek Dec 17 '21 at 12:54