Lesson 6 of 9 · 27m
Form-Associated Custom Elements and ElementInternals
How custom elements participate in native forms, validation, autofill, disabled states, reset behavior, and accessibility.
Before ElementInternals, custom inputs were second-class citizens: they looked like fields but didn't submit, reset, validate, or participate in forms correctly. Form-associated custom elements close most of that gap — and expose sloppy encapsulation immediately.
Opt in explicitly
class RatingInput extends HTMLElement {
static formAssociated = true;
constructor() {
super();
this._internals = this.attachInternals();
this._value = "";
}
}formAssociated plus attachInternals() makes the element known to the form system. It does not make the internal UI correct. Focus, naming, keyboard interaction, and validation presentation remain your responsibility.
Submit values through internals
set value(value) {
this._value = value;
this._internals.setFormValue(value);
}
get value() {
return this._value;
}Now <rating-input name="rating" value="4"> submits rating=4 with its form. setFormValue can also accept File or FormData, but most controls should submit a scalar string. Think form semantics, not application object serialization.
Use native validity plumbing
this._internals.setValidity(
{ valueMissing: true },
"Select a rating",
this.shadowRoot.querySelector("input"),
);This integrates with checkValidity(), reportValidity(), and browser blocking of invalid submission. Pass an internal anchor when possible so focus and error presentation land on the real control. Clear errors with setValidity({}) as soon as input becomes valid.
Implement the callbacks that match platform behavior
formDisabledCallback(disabled) {
this._syncDisabled(disabled);
}
formResetCallback() {
this.value = this.getAttribute("value") ?? "";
}
formStateRestoreCallback(state) {
this.value = state;
}These callbacks cover mundane moments users expect to work: a fieldset disables a subtree, reset restores initial values, and history navigation restores state. Ignoring them makes your control subtly foreign inside an ordinary form.
Labels and accessible names are still hard
A <label for="x"> outside the shadow boundary cannot label an internal input by ID. Form association helps the host participate in labeling, but internals still need names. Forward aria-label or aria-labelledby deliberately and test with a real screen reader rather than assuming attributes tunnel through.
Field notes
ElementInternalsdoes not make arbitrary elements focusable; delegate focus or managetabindexdeliberately.- Disabled controls need consistent visual, keyboard, and submission behavior — not merely a gray color.
- The
namebelongs on the outer custom element, never on an internal implementation detail consumers should not know about. - Autofill is uneven for composite controls. Test browser support before promising native-like behavior.
Was this lesson helpful?