To add interactivity to your components, you'll probably want to add some event handlers. Lit makes it easy to add a declarative event listener in the template, using an expression like this:
Here we've provided a name tag component with a message and an input element. In this step you'll use a declarative event listener so the component can handle input events.
Add a declarative event listener.
Find the input element and add a declarative event listener:
<input @input=${this.changeName} placeholder="Enter your name">
This @input expression adds this.changeName as an event listener for the input event. (You can use this syntax for any event listener—just replace input with any event name and this.changeName with any JavaScript expression that evaluates to an event handler.)
Add the event handler method.
Next, add the event handler that's called when the input value changes.
changeName(event: Event) {
constinput=event.targetasHTMLInputElement;
this.name=input.value;
}
changeName(event) {
constinput=event.target;
this.name=input.value;
}
Since name is a reactive property, setting it in the event handler triggers the component to update.
Try it out by entering a name.
For more information about declarative event handlers, see Events.