Skip to content
Go back

Hello, Web Components(1) — Basic component

Updated:

I start to learn web components and now i try to take note for my study following my mind. let’s go :)

WebComponents1

Table of contents

Open Table of contents

What is Web components?

set of web platform APIs that allow you to create new custom, reusable, encapsulated HTML tags to use in web pages and web apps. will work across modern browsers, and can be used with any JavaScript library or framework that works with HTML.

Specifications

Custom Elements

designing and using new types of DOM elements.

<hello-component></hello-component>index.html

Shadow DOM

defines how to use encapsulated style and markup in web components.

class HelloComponent extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({ mode: "open" });
    this.shadowRoot.innerHTML = `
       <div>Hello, WebComponents</div>
     `;
  }
}

customElements.define("hello-component", HelloComponent);hello-component.js

ES Modules

defines the inclusion and reuse of JS documents in a standards based, modular, performant way.

HTML Template

defines how to declare fragments of markup that go unused at page load, but can be instantiated later on at runtime.

Let’s coding

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Hello WebComponents</title>
  </head>
  <body>
    <hello-component></hello-component>
    <script type="module" src="hello-component.js"></script>
  </body>
</html>index.html

Script

class HelloComponent extends HTMLElement {
  css = `
   h1{
    font-size:16px;
  }`;

  template = () => {
    return `
     <h1>Hello news card component</h1>
     <button type="button" class="bt-count">+</button>
     <div class="count">Count: <span>${this.count}</span></div>
    `;
  };

  constructor() {
    super();
    this.count = 0;
    this.attachShadow({ mode: "open" });
  }

  //when the custom element is first connected to the document's DOM.
  connectedCallback() {
    this.createTemplate();
    this.onClickBtCount();
  }

  createTemplate() {
    this.shadowRoot.innerHTML = `
       <style>${this.css.trim()}</style>
       <link rel="stylesheet" href="hello-component.css">
        ${this.template().trim()}
     `;
  }

  //render every time that click for update value that display
  onClickBtCount() {
    this.shadowRoot.querySelector(".bt-count").addEventListener("click", () => {
      this.count++;
      this.render();
    });
  }

  render() {
    const count = this.shadowRoot.querySelector(".count span");
    count.innerHTML = this.count;
  }
}

customElements.define("hello-component", HelloComponent);hello-component.js

Style

h1 {
  color: blue;
}hello-component.css

Finally

Put everything together.

Demo

Ok, Done for basic component ;)


Edit page
Share this post on:

Previous Post
Hello, Web Components(2) — Component Generate QR Code