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
