Use properties

This documentation is a work in progress. It describes prerelease software, and is subject to change.

In this step, you’ll declare a property for your component, and use the value in the component’s template. LitElement components update automatically when their properties change.

Starting code

my-element.js

/**
 * Try LitElement https://lit-element.polymer-project.org/try
 * Starting code for 3. Properties
 */

import { LitElement, html } from '@polymer/lit-element'; 

class MyElement extends LitElement {
  /**
   * TODO: Declare a property.
   */
  static get properties() {
    return { };
  }

  /**
   * TODO: Initialize the property.
   */
  constructor() {
    // Always call superconstructor first
    super(); 
  }

  /**
   * TODO: Add a property to your template with a JavaScript expression.
   */
  render() {
    return html`
      <p></p>
    `;
  }
}
customElements.define('my-element', MyElement);

  1. Declare a property.

    In my-element.js, replace the existing properties getter with the following code:

     static get properties() {
       return {
         // Property declaration
         message: { type: String }
       };
     }
    
  2. Initialize the property.

    You should initialize property values in a component’s constructor.

    In my-element.js, replace the existing constructor with the following code:

     constructor() {
       // Always call superconstructor first
       super();
    
       // Initialize property
       this.message='Hello world! From my-element';
     }
    
  3. Add the property to your template with a JavaScript expression.

    In my-element.js, replace the existing render function with the following code:

     render() {
       return html`
         <p>${this.message}</p>
       `;
     }
    

If you’re stuck, click Launch Code Editor below to see the completed code for Step 3.

Next: 4. Logic