0

How to render component from string in litelement? It is possible or it is possible to convert string to TemplateResult?

My code not working

export class MyElement extends ScopedElementsMixin(LitElement) {
    static get scopedElements() {
        return {
          'panel-group': PanelGroup,
          'panel': Panel,
        }
      }

    static get properties() { 
        return {
            controls: { type: String }
        }
    }

    createRenderRoot() {
        return this;
    }
    
    render() {
        // example insert string
        // const controls = "<panel-group name=panel><panel key=0 panelValue=0 label=true></panel><panel key=1 panelValue=1 label=false></panel></panel-group>"

        return html`${unsafeHTML`${this.props.controls}`}`; 
    }
}
funfelfonfafis
  • 187
  • 2
  • 15

3 Answers3

0

unsafeHTML is a directive. You can use as below code.

render() {
    // example insert string
    // const controls = "<panel-group name=panel><panel key=0 panelValue=0 label=true></panel><panel key=1 panelValue=1 label=false></panel></panel-group>"

    return html`${unsafeHTML(this.props.controls)}`; 
}
Hiten B
  • 61
  • 1
  • 12
0
     render() {
    //example insert string
     const controls = "<panel-group name=panel><panel key=0 panelValue=0 label=true></panel><panel key=1 panelValue=1 label=false></panel></panel-group>"
     const component= html([controls]);
     return component; 
     }
  • Note that this approach requires that the custom element referenced in the component string has already been defined and registered with the customElements registry – Maruthupandian M Dec 27 '22 at 15:32
0

is the point to render something from an HTML string or specifically to use lit in order to do this? could use updated to respond to controls being updated and do something like

const div = document.createElement('div');
div.innerHTML = this.controls;
this.querySelector('.targetToPlaceThis').innerHTML = div.innerHTML; // (or some kind of append loop)