liveBook · Manning

attachInternals

As explained in Web Component Development with Modern Libraries and Tooling

A browser method that creates and returns an ElementInternals object for a custom element.

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

How Web Component Development with Modern Libraries and Tooling covers it

How deep it goes
Explains initialization, value updates, FormData, and reset callbacks, but does not detail broader ElementInternals capabilities.
Examples
Uses temperature-gauge, single-value controls, radio-group, and FormData entries such as color, size, and timestamp.
What it assumes
Assumes familiarity with custom elements, HTML forms, class properties, lifecycle callbacks, and FormData.
What you can do after
Apply it to build form-associated custom elements that submit one or multiple values and update them when component state changes.
How it connects
Connects custom elements with HTML forms, ElementInternals, FormData, form association, and Stencil decorators.

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.