Search code examples
typescriptkeyboardweb-componentlit

How to bind keyboard events in Template of Lit Web Component


I have a Lit web component that contains a button with a click event. Simplified, it looks like this:

<button @click=${props.onClick}>
    <!-- button content -->
</button>

The onClick function is triggered on mouse click, and even on a spacebar keypress (when the button is focused with the keyboard).
But, I also want this logic to trigger when the enter/return key is pressed on the keyboard (while the button is focused). I can't find a way to tie keyboard events to the template. In Angular I was just able to add things like: (keydown.enter)="myLogic()", but that doesn't seem to work here.

For added context, the Lit web component contains more items than just this button.

Any info on tying keyboard events to the templates of a Lit web component?


Solution

  • It's just like how you would add a click

    <button @keydown=${doSomething}>
        <!-- button content -->
    </button>