Use lit-html's @event
annotation to add an event listener to an element inside a template.
Starting code
my-element.js
{% include projects/try/events/before/my-element.js %}
{% include project.html folder="try/events/before" openFile="my-element.js" %}
Editing steps
In the element template in render
, annotate a <button>
to add an event listener:
my-element.js
render(){
return html`
...
<!-- Annotate the button to add an event listener. -->
<button></button>
`;
}
Annotated button
<button @click="${(event) => this.clickHandler(event)}">Click</button>
To handle the event, add an event handler method to the MyElement class.
my-element.js
class MyElement extend LitElement {
...
render(){
...
}
// Add an event handler here.
}
Event handler code
clickHandler(event){
console.log(event.target);
this.myBool = !this.myBool;
}
Completed code
my-element.js
{% include projects/try/events/after/my-element.js %}
{% include project.html folder="try/events/after" openFile="my-element.js" %}
{% include prevnext.html prevurl="expressions" prevtitle="Loops and conditionals" nexturl="style" nexttitle="Style your element" %}