4

I'm trying to display a custom format for my lightning web component via rendered and innerHTML of a div.

<template>
    <div class="container" lwc:dom="manual"></div>
</template>

js (data has @track):

renderedCallback() {
    if(this.data){
        const container = this.template.querySelector('.container'); 
        container.innerHTML = '<lightning-input name="test" value="' + this.data.societyID + '"></lightning-input>';
    }
}

But it's giving me no errors but also not displaying anything on my div. Is innerHTML only available for native HTML or is there a better way to achieve this?

1 Answer 1

7

You cannot create/use innerHTML for custom components (c or lightning namespace) in LWC but you can do so for native elements. Below is the detailed explanation.

lightning-input is Customized built-in element. So, you can logically (but does not work) use createElement

Customized built-in elements inherit from basic HTML elements. To create one of these, you have to specify which element they extend (as implied in the examples above), and they are used by writing out the basic element but specifying the name of the custom element in the is attribute (or property). For example , or document.createElement("p", { is: "word-count" }).

Sample:

<lightning-input></lightning-input>
<lightning-button label="Add Input" onclick={addInput}></lightning-button>
<div lwc:dom="manual" class="container"></div>

JS:

addInput() {
    let linput = document.createElement('lightning-input', { is: 'lightning-input' });
    this.template.querySelector('.container').appendChild(linput);
}

OUTPUT:

enter image description here

Why it does not work?

Although you are able to create lightning input element and add it in DOM inside div.container as shown in screenshot above, it will be missing the main content like span, label, input - it will not render. The custom lightning elements are designed and defined in such a way. For createElement to work, salesforce should release such native lightning API - you can check this answer - Not able to render dynamic Lightning Web Component from Software Architect at Salesforce (Lightning Platform).


And yes native elements can be created. For example change JS to below will work:

addInput() {
    let linput = document.createElement('input');
    this.template.querySelector('.container').appendChild(linput);
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .