liveBook · Manning

Form-associated custom element

As explained in Web Component Development with Modern Libraries and Tooling

A custom element integrated with an HTML form so it can participate in form submission and reset behavior.

A custom element placed inside a form does not submit data by default. Mark the class as form-associated, connect it to ElementInternals, and provide the value the form should submit. section 3.9

Implement form participation in these steps:

  • Declare static formAssociated = true; on the custom-element class, rather than in the constructor or an instance method. section 3.9
  • Store an ElementInternals object from attachInternals(). section 3.9
  • Call setFormValue() initially and whenever the component value changes; pass either one value or a FormData object. section 3.9
  • Use formAssociatedCallback() to save initial values and formResetCallback() to restore them when the form resets. section 3.9

Submitting a temperature gauge

For <temperature-gauge name="temperature">, calling this.#internals.setFormValue(someValue) submits one value under the key temperature. A component submitting multiple values can create FormData, set color and size entries, and pass that object to setFormValue(). section 3.9

#internals = this.attachInternals();

Inspect the ElementInternals declaration used to connect the component with form behavior. section 3.9

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Explains class declaration, ElementInternals, submitted values, and reset callbacks, but leaves callback state implementation unspecified.
Examples
Uses a temperature-gauge name attribute and FormData entries named color and size to demonstrate submitted values.
What you can do after
Build it from scratch by registering form association, setting submitted values, and restoring component state on reset.
How it connects
Connects custom elements with HTML forms, ElementInternals, FormData, lifecycle callbacks, and form reset controls.

Also explained in

Compare how 2 books explain form-associated custom element →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Web Component Development with Modern Libraries and Tooling. The section links point to the parts of the book it draws on.