liveBook · Manning

setFormValue

As explained in Web Component Development with Modern Libraries and Tooling

An ElementInternals method that sets the form-submission value or values contributed by a custom element.

setFormValue is an ElementInternals method that makes a form-associated custom element contribute one value or several values when its containing form is submitted. Call it once with the initial data and again whenever submitted data changes. section 3.9

A vanilla custom element needs three pieces:

  • Declare static formAssociated = true; the declaration must be on the class so custom-element registration can recognize it. section 3.9
  • Obtain ElementInternals with attachInternals(), then call internals.setFormValue(value). A single value uses the custom element’s name attribute as its form-data key. section 3.9
  • Pass a FormData object when the component must submit multiple values; update that object and call setFormValue again after changes. section 3.9

A component value and timestamp

A radio-group can initialize its value and timestamp in componentWillLoad, then refresh both after a selection changes: formData.set(this.name, this.value); formData.set('timestamp', Date.now().toString()); this.internals.setFormValue(formData). The component’s submitted keys must be chosen by the component because no general key-selection mechanism is prescribed. section 6.12

const formData = new FormData();
formData.set("color", someColor);
formData.set("size", someSize);
this.#internals.setFormValue(formData);

Inspect the compact FormData pattern for submitting color and size together. section 3.9

Form-associated components should also preserve initial submitted properties in formAssociatedCallback and restore them in formResetCallback. Stencil uses @AttachInternals() and the same setFormValue call, while lifecycle work moves into componentWillLoad and change handlers. section 3.9 section 6.12

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Explains class setup, ElementInternals acquisition, single and multiple values, change updates, and reset callbacks.
Examples
Uses temperature-gauge, radio-group, color and size entries, and a timestamp as submitted values.
What it assumes
Assumes familiarity with custom elements, forms, lifecycle callbacks, ElementInternals, and FormData.
What you can do after
Build it from scratch, submit custom-element values, refresh them after changes, and support form resets.
How it connects
Connects ElementInternals, custom elements, FormData, form-associated components, and Stencil.

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.