I'd like a reactive property to be "bound" to the value of an <input>
element. I can achieve this using various approaches, such as using @change(...)
, but I wonder if there is a more canonical way of doing it?
import {html, LitElement} from 'lit';
import {customElement, property} from 'lit/decorators.js';
@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
@property()
name: string = 'Somebody';
render() {
return html`
<input .value=${this.name}>
<p>Hello, ${this.name}!</p>
`;
}
}
Use input Event Listener
as follows:
import { html, css, LitElement } from 'lit';
import { customElement, property } from 'lit/decorators.js';
@customElement('simple-greeting')
export class SimpleGreeting extends LitElement {
static styles = css`p { color: blue }`;
@property()
name = 'Somebody';
render() {
return html`
<input .value=${this.name} @input=${this._onInput}>
<p>Hello, ${this.name}!</p>
`;
}
private _onInput(event: Event) {
this.name = (event.target as HTMLInputElement).value;
}
}