attachInternals() creates and returns an ElementInternals object for a custom element. A component keeps that object privately so it can participate in HTML form submission rather than behaving like an unrelated element inside the form. section 3.9
Use the method as part of the form-associated custom-element setup:
- Declare static formAssociated = true; on the custom-element class. The declaration must be static because the browser checks it during custom-element registration. section 3.9
- Store the returned object, for example with #internals = this.attachInternals();. section 3.9
- Call setFormValue() initially and whenever the component value changes. Pass one value or a FormData object containing several values. section 3.9
- Implement formAssociatedCallback and formResetCallback when submitted properties need initial-value storage and reset behavior. section 3.9
A custom temperature control
A <temperature-gauge name="temperature"> can call this.#internals.setFormValue(someValue);. On submission, the value uses the element's name attribute as its form-data key. For several values, create FormData, set entries such as color and size, and pass it to setFormValue(). In Stencil, the equivalent setup uses formAssociated: true, @AttachInternals() internals: ElementInternals;, and this.internals.setFormValue(newValue) during componentWillLoad() and after changes. section 3.9 section 6.12
#internals = this.attachInternals();
Inspect the compact initialization that obtains ElementInternals from the custom element. section 3.9
