0

I am trying to create a web component with the following features:
1. click a button to add a <textarea> element.
2. After adding text to newly created <textarea> element, this text is added to the corresponding item of this.list.
3. In a separate script be able to get the DOM element with document.querySelector() and then retrieve the data from this.list.
Here is what I have so far:

<!DOCTYPE html>
<html>
  <body>
    <my-element></my-element>
    <script type="module">
      import { LitElement, html } from "lit-element";
      import { repeat } from "lit-html/directives/repeat.js";

      class MyElement extends LitElement {
        static get properties() {
          return {
            list: { type: Array },
          };
        }
        constructor() {
          super();
          this.list = [
            { id: "1", text: "hello" },
            { id: "2", text: "hi" },
            { id: "3", text: "cool" },
          ];
        }
        render() {
          return html`
            ${repeat(this.list, item => item.id,
              item => html`<textarea>${item.text}</textarea>`
            )}
            <button @click="${this.addTextbox}">Add Textbox</button>
          `;
        }
        addTextbox(event) {
          const id = Math.random();
          this.list = [...this.list, { id, text: "" }];
          console.log(this.list); // text from new textboxes is not being added to list
        }
      }
      customElements.define("my-element", MyElement);
      </script>
      <script>
        const MyElement = document.querySelector("my-element");
        const data = MyElement.properties; // undefined
      </script>
  </body>
</html>
Max888
  • 3,089
  • 24
  • 55

1 Answers1

0

Here an example of how to retrieve data from LitElement ;

Demo

import { LitElement, html } from "lit-element";


class MyElement extends LitElement {
  static get properties() {
    return {
      list: { type: Array },
    };
  }
  constructor() {
    super();
    this.list = [
      { id: "1", text: "hello" },
      { id: "2", text: "hi" },
      { id: "3", text: "cool" },
    ];
  }
  render() {
    return html`

      ${this.list.map( item=> html`${item.id}. ${item.text}<br>`)}


     <button @click="${this.addTextbox}">Add Textbox</button>
    `;
  }

  addTextbox(event) {
    const id = Math.random();
    this.list = [...this.list, { id, text: "" }];
    console.log(this.list); // text from new textboxes is not being added to list
    this.dispatchEvent(new CustomEvent('changed',{ bubles:true,composed:true, detail:{list:this.list}}));

  }

}
customElements.define("my-element", MyElement);

  const MyElement = document.querySelector("my-element");
  MyElement.addEventListener('changed',function(e){ 
    const list = e.detail.list;
    console.log('out->',list);

  });
Cappittall
  • 3,300
  • 3
  • 15
  • 23