custom components - how to clone html template defined as js string literal?

586 Views Asked by At

I'm trying to understand how the different parts of vanilla web components work together. I have defined a simple custom component and am trying to include a template. I'm doing this since many browser vendors are not supporting html imports and moving towards using es6 modules instead. Here's my web component:

var tmpl = `<template>
<h1>header</h1>
<p>copy</p>
</template>`;

class MyComponent extends HTMLElement {
    constructor() {
        super();
    }
    connectedCallback() {
        let z = tmpl.cloneNode(true);
        this.appendChild(z);
    }
}

customElements.define('my-comopnent', MyComponent);

The error I get is Uncaught Type Error: cloneNode is not a function I imagine that has something to do with the way I am defining my template as a string.

My question is this: how do I stamp out my template in a custom component where the template is defined as a javascript string literal? Can I do so without additional dependencies or npm libraries?

1

There are 1 best solutions below

6
On BEST ANSWER

Looking at https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode cloneNode is a method that is on the Node interface.

In your code tmpl is not a Node but a string.

You need to do something like this at the top of your code:

let tmpl = document.createElement('template');
tmpl.innerHTML = `
<h1>header</h1>
<p>copy</p>
`;