Limitations and Workarounds
Web components have platform limits that affect accessibility, forms, typing, and the lifecycle. Each section below names one limit, the workaround, and its tradeoffs.
Form Components and Accessibility
Problem
A form component keeps its input in its shadow root, and the browser does not give the host's aria-label, aria-labelledby, aria-describedby, or <label> to that input.
Workaround
Copy the host's names to the input one frame after connect, when one of the attributes changes, and when the input gets focus. While the host has no aria-label, aria-labelledby, or aria-describedby, give it the none role to keep screen readers from reading it as a second named node:
class MyFormComponent extends HTMLElement { static formAssociated = true; static observedAttributes = ["id", "aria-label", "aria-labelledby", "aria-describedby"];
readonly #internals = this.attachInternals();
connectedCallback(): void { // Pick up a label that the page adds in the same task requestAnimationFrame(() => this.#forwardAria());
// Pick up a label that the page adds later this.#customFormElement.addEventListener("focusin", this.#forwardAria); }
attributeChangedCallback(): void { if (this.isConnected) { this.#forwardAria(); } }
#forwardAria = (event?: FocusEvent): void => { // Skip focus that moves inside the element if (this.#customFormElement.contains(event?.relatedTarget as Node | null)) return;
// Forward labels const labelElements = [...this.#internals.labels]; const hostNameElements = this.ariaLabel ? [this] : labelElements.length > 0 ? labelElements : null;
this.#customFormElement.ariaLabelledByElements = this.ariaLabelledByElements ?? hostNameElements; this.#customFormElement.ariaDescribedByElements = this.ariaDescribedByElements;
// Avoid double read const hostRole = this.ariaLabel || this.ariaLabelledByElements || this.ariaDescribedByElements ? null : "none";
// Firefox builds the field again on each role write if (this.#internals.role !== hostRole) { this.#internals.role = hostRole; } };}The input points at the <label> elements and not at the host, because Firefox and WebKit do not read a name that the host gets from a <label> through aria-labelledby. The $forwardAria macro builds this code for you.
Tradeoffs
- It needs
ariaLabelledByElements, which is Baseline since April 2025: Chrome 135, Firefox 136, and Safari 16.4. - A
<label for>, or anaria-labelledbyoraria-describedbytarget, that the page adds or removes later takes effect only when the input gets focus. - With
aria-label,aria-labelledby, oraria-describedbyon the host, VoiceOver with Safari, NVDA with Edge, and Orca with Firefox read the name twice. - A wrapping
<label>is not supported, because its name includes the host's shadow content.
Validation Messages
Problem
ElementInternals.setValidity() throws a TypeError when a flag is true and the message is empty, and no API returns the browser's own validation messages. A hardcoded message stays in one language, while native fields show theirs in the browser's language.
Workaround
Keep a detached native field that matches the component, copy the state that validation reads to it, and pass its validity and validationMessage to setValidity(). Forward setCustomValidity() to the detached field to keep the custom error in the same validity:
class MyCheckbox extends HTMLElement { readonly #internals = this.attachInternals(); readonly #validityCheckboxEl = Object.assign(this.ownerDocument.createElement("input"), { type: "checkbox" });
setCustomValidity(message: string): void { this.#validityCheckboxEl.setCustomValidity(message); this.#syncValidity(); }
#syncValidity() { const validityCheckbox = this.#validityCheckboxEl; validityCheckbox.required = this.required; validityCheckbox.checked = this.checked;
this.#internals.setValidity(validityCheckbox.validity, validityCheckbox.validationMessage); }}Pick the field by what the component does:
| Component | Detached field | State to copy |
|---|---|---|
| Text or number | <input> | required, and value as a string |
| Checkbox, switch | <input type="checkbox"> | required, checked |
| Select, list | <select> with { multiple: true, length: 1 } | required, and selectedIndex as 0 with a value or -1 without |
Tradeoffs
- No native field reports
badInputfor a value the component does not offer, like an unknown option.
Submitting a Form with Enter
Problem
In a native field, Enter submits the form through implicit submission. The browser runs it only for native form controls, and ElementInternals has no option to turn it on for a form-associated custom element.
Calling form.requestSubmit() on Enter is not the same:
- It submits even when the default submit button is disabled.
event.submitterisnull, and the button'sname,value, andformactionare lost.- The app's listeners on the host cannot cancel the key with
preventDefault(), because the component's listener runs first.
Workaround
Wait one task to let the app's listeners cancel the key, and then click the form's default button. Like in a native field, a disabled default button blocks the submit:
class MyFormComponent extends HTMLElement { #onKeyDown = (event: KeyboardEvent) => { if (event.key !== "Enter" || event.isComposing) return;
// Let the app's listeners cancel the key first setTimeout(() => { const form = this.form; if (event.defaultPrevented || !form) return;
const formControls = [...form.elements] as HTMLButtonElement[]; const defaultButton = formControls.find(control => control.type === "submit");
if (defaultButton) { defaultButton.click(); } else { form.requestSubmit(); } }, 0); };}The $submitImplicitly macro builds the timeout part for you.
Tradeoffs
- Without a submit button, a native field submits only when the form has one text-like field, but this code always submits.
- An image button is never the default button, because
form.elementsleaves out<input type="image">. - In Safari before 27, the
Enterthat ends an IME composition hasisComposingset tofalseand submits the form.
Focusing Components with Shadow DOM
Problem
Tab reaches a focusable control inside a component's shadow root, but focus() on the host does not move focus to that control. A custom element host is also not in the sequential focus order without a tabindex.
Workaround
Attach the shadow root with delegatesFocus to forward focus on the host to the first focusable element inside it, and give the host tabindex="0" when the page sets none:
class MyFocusableComponent extends HTMLElement { readonly #shadow = this.attachShadow({ mode: "open", delegatesFocus: true, });
connectedCallback(): void { // Keep a tabindex that the page sets if (!this.hasAttribute("tabindex")) { this.tabIndex = 0; } }}A tabindex that the page sets stays, also tabindex="-1".
Tradeoffs
- Focus goes to the first focusable element in shadow tree order. With more than one focusable element, put the one that should take focus first.
delegatesFocuscan only be set when the shadow root is attached.
Properties Set Before Element Upgrade
Problem
A framework, like Angular, or a script can set a property on a component before its class upgrades the element, and the value lands on the instance as a plain own property that hides the setter.
Workaround
Capture the own properties in the first class field, and on connect delete each one and set it again to run the setter:
class MyComponent extends HTMLElement { // Runs before any other field can overwrite an early value #capturedProperties = Object.entries(this) as [keyof this, this[keyof this]][];
connectedCallback() { for (const [property, value] of this.#capturedProperties) { // Remove the own property that hides the setter delete this[property]; this[property] = value; }
// Make a later connect do nothing this.#capturedProperties.length = 0; }}The $upgrade macro builds this code for you:
class MyComponent extends HTMLElement { connectedCallback() { $upgrade(); }}Tradeoffs
#capturedPropertiesmust be the first field in the class. A field declared before it runs its initializer first and can overwrite an early value before the capture.- Only enumerable own properties are captured, and a property set with
Object.definePropertyandenumerable: falsebefore the upgrade stays as it is.
DOM Children Unavailable in connectedCallback
Problem
When a blocking <script> defines the component before the markup that uses it, connectedCallback runs before the parser adds the children:
<!-- Defines the component before its children are parsed --><script src="path/to/web-component.js"></script>
<my-component> <span class="child"></span></my-component>class MyComponent extends HTMLElement { connectedCallback() { const child = this.querySelector(".child"); // null }}Workaround
- Slotted children: listen for
slotchangeon the<slot>. It fires once the slotted children are there, however the script loads. - Children read with
querySelector: wait forDOMContentLoadedwhile the document is still loading, and run at once otherwise:
class MyComponent extends HTMLElement { connectedCallback() { if (document.readyState === "loading") { document.addEventListener("DOMContentLoaded", () => this.#init(), { once: true }); } else { this.#init(); } }
#init() { const child = this.querySelector(".child"); }}Tradeoffs
slotchangecovers only the slotted children themselves, and their descendants may not be parsed yet when it fires.
Text Changes in Slotted Content
Problem
slotchange fires only when nodes are added to or removed from a slot, not on a text change in place, like a framework that updates the nodeValue of a text node or text added inside a slotted element. A component that reads slotted text, like to tell a text button from an icon-only one, keeps its old state.
Workaround
Replace the slotted node instead of editing its text to fire slotchange. To follow every edit, observe the host with a MutationObserver:
class MyComponent extends HTMLElement { constructor() { super();
new MutationObserver(() => this.#syncLabel()).observe(this, { characterData: true, childList: true, subtree: true, }); }}Tradeoffs
- The observer runs on every change inside the host, also on changes the component does not care about. For most components, a text edit in place is too rare to be worth that cost.
Flash of Unstyled Content
Problem
Until the component's script defines the element, the element renders without its styles and behavior, and the page shows a flash of unstyled content (FOUC).
Workaround A: Blocking Script
Load the component with a classic blocking <script> before the markup that uses it, to define it before the parser reaches the element:
<script src="path/to/my-component.js"></script><my-component></my-component>Tradeoff: Not every framework lets you control the order of scripts, and a blocking script delays the first render of the page.
Workaround B: Hide Until Defined
Hide the element with the :not(:defined) selector until its definition is registered:
my-component:not(:defined) { display: none;}Tradeoff: The element takes its space only once the definition loads, and the layout shifts.
Writing HTML and CSS as Strings
Problem
HTML and CSS written as strings inside a component get no type checking, linting, minification, or editor support, and their errors show only at runtime.
Workaround
Keep the HTML and CSS in their own files, with linting and type checking, and inline them with $inline(filePath). The build replaces each call with the minified file contents:
class MyComponent extends HTMLElement { static readonly #template = (() => { const template = document.createElement("template"); template.innerHTML = "<style>" + $inline("./my-component.css") + "</style>" + $inline("./my-component.html"); return template; })();
readonly #shadow = (() => { const shadow = this.attachShadow({ mode: "open" }); shadow.append(MyComponent.#template.content.cloneNode(true)); return shadow; })();}The $shadow macro builds this code for you.
TypeScript Types
Problem
Unlike the props of a TSX component, the types of a custom element are not picked up on their own. The native DOM APIs, like querySelector and createElement, and each framework need their own type definitions, and without them consumers get no type safety on properties, attributes, or events.
Workaround
Export a [ComponentName]Types type from the component file with SV.WComponent. List in ExtendAttribute the attributes that TypeScript cannot infer from the class, like an attribute with a string union or one whose type differs from its property. Type a boolean attribute as SV.BooleanAttribute, which leaves out "false", because an attribute that is present is on, whatever its value:
import type { SV } from "@staticview/ui";
interface ExtendAttribute { orientation: "horizontal" | "vertical"; disabled: SV.BooleanAttribute;}
export type SegmentedControlTypes = SV.WComponent<typeof SegmentedControl, ExtendAttribute>;
class SegmentedControl extends HTMLElement implements SV.IWebComponent {}The CLI generates the .d.ts files of each target from this export, and the Setup pages show how to use them with native DOM types and with each framework.
Accessor Types
TypeScript records a separate write type for an accessor whose setter accepts more than its getter returns, but only an assignment expression reaches it. Every other route, like an indexed access, a keyof, or a mapped type, yields the getter type, and WComponent reads the class through mapped types. Since no type operator extracts a setter type, declare the wider type by hand in the third type argument:
interface OverriddenProperties { for: HTMLElement | HTMLElement[] | string | null;}
export type MyTooltipTypes = SV.WComponent<typeof MyTooltip, ExtendAttribute, OverriddenProperties>;
class MyTooltip extends HTMLElement implements SV.IWebComponent { get for(): HTMLElement[] { return this.#anchorElements; } set for(value: HTMLElement | HTMLElement[] | string | null) { this.#setAnchorElements(value); }}Without it, no generated framework type lets consumers assign a selector string to for. When the component has no added attributes, pass never as the second type argument.
The generated API reference reads both accessors from the class and shows the setter type as Setter Type.
Tradeoffs
- The types are generated, not inferred, and need to be generated again whenever the component API changes.
- Keep
ExtendAttributeandOverriddenPropertiesin sync with the class by hand, because the type system cannot check an attribute that the class does not declare or a wider setter type.