Use properties
In this step, you’ll declare a property for your component, initialize the property, and use the value in the component’s template.
Starting code
my-element.js
import { LitElement, html } from 'lit-element';
class MyElement extends LitElement {
// TODO: Create a `properties` getter; declare a property
// TODO: Add a constructor; initialize the property
render() {
return html`
<!-- TODO: Replace text content with your property -->
<p>Hello world! From my-element</p>
`;
}
}
customElements.define('my-element', MyElement);
-
Declare a property.
In my-element.js, add the following
properties
getter to theMyElement
class:static get properties() { return { message: { type: String } }; }
The code snippet above adds a string property called
message
to your element class. -
Initialize the property.
A good place to initialize property values is in your element constructor.
In my-element.js, add the following method to the
MyElement
class:constructor() { super(); this.message = 'Hello world! From my-element'; }
The first line of code in the constructor (
super();
) calls the parent class constructor. -
Add the property to your template.
You can add properties to your LitElement templates with JavaScript expressions.
In my-element.js, replace the existing
render
function with the following code:render() { return html` <p>${this.message}</p> `; }
LitElement components update automatically when their properties change.
Here’s the completed code for this step:
my-element.js
import { LitElement, html } from 'lit-element';
class MyElement extends LitElement {
static get properties() {
return { message: { type: String } };
}
constructor() {
super();
this.message='Hello world! From my-element';
}
render() {
return html`
<p>${this.message}</p>
`;
}
}
customElements.define('my-element', MyElement);