Handling conditionals and loops in your LitElement templates is easy. No special annotations, just plain JavaScript expressions.
Starting code
my-element.js
{% 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.
my-element.js
constructor(){
super();
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
.
my-element.js
render(){
return html`
<p>${this.message}</p>
<!-- Add a loop and a conditional here. -->
`;
}
Code for loop
<ul>
${this.myArray.map(i => html`<li>${i}</li>`)}
</ul>
Code for conditional
${this.myBool?
html`<p>Render some HTML if myBool is true</p>`:
html`<p>Render some other HTML if myBool is false</p>`}
Completed code
my-element.js
{% 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" %}