Missing styles for Spectrum Web Compontents
When Spectrum Web Components generated via script, they sometimes lose their styling. (See attached screen recordings.)
The elements are inserted using a template element, which is likely causing this problem.
index.html
<sp-theme theme="spectrum" color="light" scale="medium" dir="ltr">
<main>
<sp-button id="refesh-button">Refesh</sp-button>
<div id="refesh-area">
<!-- generated elements -->
</div>
<template id="input-item-template">
<div class="input-item">
<sp-field-label class="input-label">Label</sp-field-label>
<sp-textfield></sp-textfield>
</div>
</template>
</main>
</sp-theme>
create.js
const inputItemTemplateElem = document.getElementById("input-item-template");
for(let i=0; i<20; i++) {
const inputItemFrag = inputItemTemplateElem.content.cloneNode(true);
if(!inputItemFrag || !(inputItemFrag instanceof DocumentFragment)) {
console.error("Error when cloning the template.");
return;
}
const inputLabelElem = inputItemFrag.querySelector(".input-label");
inputLabelElem.textContent = "Label " + ++labelIndex;
refeshAreaElem.appendChild(inputItemFrag);
}
I haven’t noticed it yet when I insert the elements one by one.
for(let i=0; i<20; i++) {
const inputItem = document.createElement("div");
const inputLabelItem = document.createElement("sp-field-label");
inputLabelItem.textContent = "Label " + ++labelIndex;
const inputElem = document.createElement("sp-textfield");
inputItem.appendChild(inputLabelItem);
inputItem.appendChild(inputElem);
refeshAreaElem.appendChild(inputItem);
}
You can find the sample plugin attached to this post: https://forums.creativeclouddeveloper.com/t/missing-styles-for-spectrum-web-compontents/11585
What is the desired outcome:
SWC elements should also be able to be inserted via a template element using JavaScript without losing their styles.
1
vote