Skip to content

What is a recommended default template

Gabriel Forti edited this page Jul 31, 2018 · 3 revisions

At the very minimum you can use this code just for the HTML. This does not include the callbacks.

You can omit (async () => { ... })(); if you are using imports

(async () => {

    function generateTemplate() {

        const template = document.createElement('template')

        template.innerHTML = `
            <style>                
                :host { }
            </style>
            <div>
                <slot></slot>
            </div>
        `;
        return template
    }

  class CustomComponent extends HTMLElement {
      
    constructor() {
      super()
      const shadowRoot = this.attachShadow({ mode: 'open' })
      shadowRoot.appendChild(generateTemplate().content.cloneNode(true))
    }
   
  }

  window.customElements.define('custom-component', CustomComponent)
})();

For a more full featured template something like this can work.

(async () => {
    /*
     * <custom-component></custom-component>
     * <script src="custom-component.element.js"></script>
     */
    function generateTemplate() {

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

        template.innerHTML = `
            <style>
                :host h1 {
                  color: var(--on-primary, red);
                  font-size: 2.5rem;                  
                }
            </style>
            <article>
                <h1>CustomComponent</h1>
                <slot></slot>
            </article>
        `;
        return template;
    }

  class CustomComponent extends HTMLElement {

    constructor() {
      super();
      const shadowRoot = this.attachShadow({ mode: 'open' });
      shadowRoot.appendChild(generateTemplate().content.cloneNode(true));
    }

    connectedCallback() {
        console.log('Custom element added to page.');
        this.render()
    }

    disconnectedCallback() {
      // remove event listeners
        console.log('Custom element removed from page.');
    }

    adoptedCallback() {
        console.log('Custom element moved to new page.');
    }

    static get observedAttributes() {
      return [];
    }

    attributeChangedCallback(attr, oldValue, newValue) {
        if ( oldValue !== newValue) {
            this.render()
        }
        console.log(`${attr} was changed from ${oldValue} to ${newValue}!`)
    }

    render() {
        // This is not required nor standard
    }

  }

  window.customElements.define('custom-component', CustomComponent);
})();