Logic in templates

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

In this step, you’ll add a loop and a conditional to your LitElement template.

Starting code

my-element.js

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

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

class MyElement extends LitElement {
  static get properties() {
    return {
      message: { type: String },
      myBool: { type: Boolean },
      myArray: { type: Array }
    };
  }
  constructor() {
    super();
    this.message='Hello world! From my-element';
    this.myBool = true;
    this.myArray = ['an','array','of','test','data'];
  }

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

      <!-- TODO: Add a loop -->

      <!-- TODO: Add a conditional -->
    `;
  }
}
customElements.define('my-element', MyElement);

  1. Add a loop to your template.

    We’ve added an array property, myArray, to my-element.js. To loop over myArray, add the following code to your template:

     <ul>
       ${this.myArray.map(i => html`<li>${i}</li>`)}
     </ul>
    
  2. Add a conditional to your template.

    We’ve added a boolean property, myBool, to my-element.js. To render conditionally on myBool, add the following code to your template:

     ${this.myBool?
       html`<p>Render some HTML if myBool is true</p>`:
       html`<p>Render some other HTML if myBool is false</p>`}
    

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

Next: 5. Events