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:
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);
}