Search code examples
javascriptpolymerlit-elementlit-html

Viewing the value of an element in litElement


I have a very simple element that wrap an <input type="range"> element. Coming from Polymer, I am having a bit of a hard time adjusting. I want to display the value of the range.

This is what I came up with:

import { LitElement, html } from 'lit-element'

class InputRange extends LitElement {
  static get properties () {
    return {
      shownValue: {
        type: String,
        attribute: false
      }
    }
  }

  firstUpdated () {
    console.log(this.shadowRoot.querySelector('#native').value)
    this.shownValue = this.shadowRoot.querySelector('#native').value
  }

  render () {
    return html`
      <input value="10" @change=${this.updateShownValue} type="range" id="native">
      <span>VALUE: ${this.shownValue}</span>
              `
  }

  updateShownValue (e) {
    this.shownValue = e.srcElement.value
    console.log(e.srcElement.value)
    // e.srcElement.value = 80
  }
}
window.customElements.define('input-range', InputRange)

And then using it:

    <script type="module" src="./InputRange.js"></script>
    <h2>Range</h2>
    <input-range id="input-range"></input-range>

Question:

Is this the right way of doing it? lit-element's documentation states clearly During an update, only the parts of the DOM that change are re-rendered. To get the performance benefits of this model, you should design your element’s template as a pure function of its properties. But does that mean that I necessarily need to 1) set shownValue at fistUpdated() 2) listen to the change event for it and update shownValue accordingly? If that is the case, am I doing it right? Or, is there a better way of doing it?

I have a glitch for it: https://glitch.com/~busy-sternum


Solution

  • I would do only some minor adjustments

    import { LitElement, html } from 'lit-element'
    
    class InputRange extends LitElement {
      static get properties () {
        return {
          shownValue: {
            type: String,
            attribute: false
          }
        }
      }
    
      constructor () {
        this.shownValue = 10;
      }
    
      render () {
        return html`
          <input value="${this.shownValue}" @change=${this.updateShownValue} type="range" id="native">
          <span>VALUE: ${this.shownValue}</span>
                  `
      }
    
      updateShownValue (e) {
        this.shownValue = e.srcElement.value
        console.log(e.srcElement.value)
      }
    
      anotherFunction () {
          this.shownValue = 80;
      }
    }
    window.customElements.define('input-range', InputRange)