Method to display child elements in WebComponent
P粉514001887
P粉514001887 2023-09-04 09:18:39
0
1
538
<p>I'm trying to rebuild a React component into a WebComponent in order to get rid of the dependency on React. </p> <p>I would like to see a WebComponent like this in HTML: </p> <pre class="brush:php;toolbar:false;"><editable-h1>Hello, world</editable-h1></pre> <p>It should look like this:</p> <pre class="brush:php;toolbar:false;"><span> <h1>Hello, world</h1> <button onClick=this.onEdit>Edit</button> </span></pre> <p>If I click the edit button, I want it to appear like this: </p> <pre class="brush:php;toolbar:false;"><form> <input type='text' value='Hello, world'></input> <button onClick=this.onSave>Save</button> </form></pre> <p>Clicking the Save button will save the changes to the database via an API call and return to the original rendering (but with the text already edited). </p> <p>I believe I can handle switching rendering and making API calls, but what I'm confused about is how to get the child element text "Hello, world" from the initial WebComponent in order to render. </p>
P粉514001887
P粉514001887

reply all(1)
P粉094351878

Trigger the connectedCallback event on open tag<editable-h1>

So your

Hello World’s innerHTML has not been parsed

To wait until parsing is completed before executing, use

setTimeout

NOTE: All tools and libraries that provide

parsedCallback will use a similar trick under the hood, using requestAnimationFrame or MutationObserver (there are many more lines of code) .

If you think one line of

setTimeout is a hack, or you don't want to waste that millisecond using setTimeout, you can check out Andrea Giammarchi's html- parsed-element code (Of course it requires loading and parsing, and it also increases dependencies and code complexity, so it takes more time overall)

And follow WC experts, this discussion continues:


Need a callback function to execute after the child element changes or parsing is completed https://github.com/WICG/webcomponents/issues/809

All methods boil down to the same goal: Wait for the event loop to be empty

What is an event loop?

https://www.youtube.com/watch?v=8aGhZQkoFbQ

customElements.define("editable-h1", class extends HTMLElement {
  connectedCallback() {
    setTimeout(() => {
      this.innerHTML = `<h1>${this.innerHTML}</h1><button>Edit</button>`;
      
      let h1     = this.querySelector("h1");
      let button = this.querySelector("button");
      
      button.onclick = (evt) => {
        button.innerHTML = (h1.contentEditable = !h1.isContentEditable) 
                              ? (h1.focus(),"Save")
                              : "Edit";
      }
      
    });
  }
});
<editable-h1>Hello World!</editable-h1>

<editable-h1>Hello Web Components World!</editable-h1>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template