Search code examples
javascripthtmllit

How can I modify properties of an element inside an html template?


I have an html template stored in a variable:

const myTemplate = html`
    <my-component>
    </my-component>
`

and I would like to add a property to myTemplate.

Something like

myTemplate.foo = "bar"

But this references the template rather than the element; how can I isolate the element to modify it?


Solution

  • For this kind of cases, you would normally use a function that returns the template.

    const myTemplate = (props) => {
      return html`<my-component foo=${props.foo} .bar=${props.bar}></mycomponent>`;
    };
    const instance = myTemplate({foo: 'some value', bar: 3});
    const otherInstance = myTemplate({foo: 'other value', bar: 42});