Handling conditionals and loops in your LitElement templates is easy. No special annotations, just plain JavaScript expressions.

Starting code


{% include projects/try/expressions/before/my-element.js %}

{% include project.html folder="try/expressions/before" openFile="my-element.js" %}

Editing steps

In this step, you'll modify the element template to add:

  • A loop using an array property.
  • An "if" statement using a boolean property.

We've decleared the properties; all you need to do is initialize them and use them in markup.

In my-element.js, add the initialization code to the constructor.


  this.message='Hello world! From my-element';

  // Initialize myArray and myBool here.


Initialization code

this.myArray = ['an','array','of','test','data'];
this.myBool = true;

In my-element.js, add a loop and a conditional to the element template in render.


  return html`

    <!-- Add a loop and a conditional here. -->

Code for loop

  ${this.myArray.map(i => html`<li>${i}</li>`)}

Code for conditional

  html`<p>Render some HTML if myBool is true</p>`:
  html`<p>Render some other HTML if myBool is false</p>`}

Completed code


{% include projects/try/expressions/after/my-element.js %}

{% include project.html folder="try/expressions/after" openFile="my-element.js" %}

{% include prevnext.html prevurl="properties" prevtitle="Declare properties" nexturl="events" nexttitle="Add an event handler" %}