Events

In this step, you’ll use lit-html’s @event annotation to add an event listener to an element inside your template. You’ll also add an event handler method to your class which will fire whenever the event occurs.

Starting code

my-element.js

import { LitElement, html } from '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.myArray = ['an','array','of','test','data'];
    this.myBool = true;
  }
  render() {
    return html`
      <p>${this.message}</p>
      <ul>${this.myArray.map(item => html`<li>${item}</li>`)}</ul>
      ${this.myBool ?
        html`<p>Render some HTML if myBool is true</p>` :
        html`<p>Render some other HTML if myBool is false</p>`}
      <!-- TODO: Add a button with an event listener -->
    `;
  }
  // TODO: Add an event handler
}
customElements.define('my-element', MyElement);

Code Editor not supported on this browser
  1. Add a button with an event listener to your template.

    In my-element.js, add the following <button> element to your HTML template:

    <button @click=${this.clickHandler}>Click</button>
    

    The binding syntax @click=${this.clickHandler} adds a listener for the click event, which calls the clickHandler method.

  2. Add the clickHandler method to your class.

    Add the following method to your MyElement class:

     clickHandler(event) {
       console.log(event.target);
       this.myBool = !this.myBool;
     }
    

    The clickHandler method toggles the boolean property, myBool, which you defined in the previous step.

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 },
      myBool: { type: Boolean },
      myArray: { type: Array }
    };
  }
  constructor() {
    super();
    this.message = 'Hello world! From my-element';
    this.myArray = ['an','array','of','test','data'];
    this.myBool = true;
  }
  render() {
    return html`
      <p>${this.message}</p>
      <ul>${this.myArray.map(item => html`<li>${item}</li>`)}</ul>
      ${this.myBool ?
        html`<p>Render some HTML if myBool is true</p>` :
        html`<p>Render some other HTML if myBool is false</p>`}
      <button @click=${this.clickHandler}>Click</button>
    `;
  }
  clickHandler(event) {
    console.log(event.target);
    this.myBool = !this.myBool;
  }
}
customElements.define('my-element', MyElement);

Next: 5. Style