On this page:
- Bind to text content
- Bind to an attribute
- Bind to a Boolean attribute
- Bind to a property
- Bind to an event handler
You can insert JavaScript expressions as placeholders for HTML text content, attributes, Boolean attributes, properties, and event handlers.
- Text content:
<p>${...}</p>
- Attribute:
<p id="${...}"></p>
- Boolean attribute:
?checked="${...}"
- Property:
.value="${...}"
- Event handler:
@event="${...}"
JavaScript expressions can include your element's properties. LitElement observes and reacts to property changes, so your templates update automatically.
Data bindings are always one-way (parent to child). To share data from a child element to its parent, use events.
Bind to text content
Bind prop1
to text content:
html`<div>${this.prop1}</div>`
Bind to an attribute
Bind prop2
to an attribute:
html`<div id="${this.prop2}"></div>`
Attribute values are always strings, so an attribute binding should return a value that can be converted into a string.
Bind to a boolean attribute
Bind prop3
to a boolean attribute:
html`<input type="checkbox" ?checked="${this.prop3}">i like pie</input>`
Boolean attributes are added if the expression evaluates to a truthy value, and removed if it evaluates to a falsy value.
Bind to a property
Bind prop4
to a property:
html`<input type="checkbox" .value="${this.prop4}"/>`
Bind to an event handler
Bind clickHandler
to a click
event:
html`<button @click="${this.clickHandler}">pie?</button>`
The default event context for @event
expressions is this
, so there is no need to bind the handler function.
Examples
my-element.js
{% include projects/docs/templates/databinding/my-element.js %}
{% include project.html folder="docs/templates/databinding" openFile="my-element.js" %}