Search code examples
htmlcomponentsweb-component

Attributes in Web Components do not show up


This is my HTML with a custom web component.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Advanced ToDo App with Web Components</title>
  </head>
  <body>
    <todo-item todo="Walk the dog" data-id="1"></todo-item>

    <script src="../static/listItems.js"></script>
  </body>
</html>

This is my JS file where I set up the component.

const template = document.createElement("template");

template.innerHTML = `<style>
h4 {
    color: white;
    font-size: 14px;
    display: block;
    padding: 10px 5px;
    background: orange;
}
</style>
<div class="todo-item">
    <h4></h4>
</div>
`;

class TodoItem extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({ mode: "open" });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
    this.shadowRoot.querySelector("h4").innerText = this.getAttribute("todo");
  }

  connectedCallback() {
    this.shadowRoot
      .querySelector(".todo-item")
      .addEventListener("click", () => {
        console.log(this.getAttribute("data-id"));
      });
  }
}

window.customElements.define("todo-item", TodoItem);

// Über Daten iterieren

const body = document.querySelector("body");

const dummydata = [
  { id: 1, description: "Walk the dog" },
  { id: 2, description: "Play football" }
];

for (item of dummydata) {
  console.log(item.description);
  todoItem = document.createElement("todo-item");
  todoItem.setAttribute("todo", item.description); # Does not work!
  todoItem.setAttribute("data-id", item.id);

  body.appendChild(todoItem);
}

The component in the HTML works perfectly fine, but when I try to create them dynamically with JavaScript setting the attributes seem not to work. The "todo"-text does not get displayed. Is setting this "todo" attribute invalid?


Solution

  • Got it - the attribute has to be set inside the connectedCallBack function. When doing it before the attribute valu will be null

      connectedCallback() {
        this.shadowRoot
          .querySelector(".todo-item")
          .addEventListener("click", () => {
            console.log(this.getAttribute("data-id"));
          });
        this.shadowRoot.querySelector("h4").innerText = this.getAttribute("todo");
      }