Search code examples
javascriptecmascript-6polymerlit-element

ternary code to change checkbox in template string in Javascript


I'm working with polymer and lit-element. In the render function I have a template string as follow:

render() {
    this.todoItem = JSON.parse(this.todoItem);
    return html`
      <li>
        ${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
        <input
          type="checkbox"
          checked="${this.todoItem.done} ? 'true' : 'false'"
          @click="${this.changeStatus}"
        />
      </li>
    `;
  }

I know this won't work because based on several stackoverflow answers, any value that you put checked equal to is going to mark it as checked.

If I do this:

<input type="checkbox" ${this.todoItem.done} ? 'checked' : ''" @click="${this.changeStatus}"/>

I get an error

TypeError: Failed to set the 'currentNode' property on 'TreeWalker': The provided value is not of type


Solution

  • After following the docs I found my answer: I had to use html https://lit-element.polymer-project.org/guide/templates. The following codes work.

    render() {
        this.todoItem = JSON.parse(this.todoItem);
        return html`
          <li>
            ${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
            ${this.todoItem.done
              ? html`
                  <input type="checkbox" checked @click="${this.changeStatus}" />
                `
              : html`
                  <input type="checkbox" @click="${this.changeStatus}" />
                `}
          </li>
        `;
      }
    

    UPDATE

    render() {
        this.todoItem = JSON.parse(this.todoItem);
        return html`
          <li>
            ${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
            ${html`
              <input type="checkbox" ?checked="${this.todoItem.done}" @click="${this.changeStatus}" />
            `}
          </li>
        `;
      }
    

    UPDATE V2

    render() {
        this.todoItem = JSON.parse(this.todoItem);
        return html`
          <li>
            ${this.todoItem.item} <button @click="${this.onRemove}">Remove</button>
            <input type="checkbox" ?checked="${this.todoItem.done}" @click="${this.changeStatus}" />
          </li>
        `;
      }