<meta form-associated>

The form-associated meta tag declares that a component is a custom form control. This allows it to participate in <form> elements.

Syntax

<meta form-associated>

Attributes

This meta tag has no additional attributes beyond it main attribute.

form-associated
A boolean attribute. If it is present, the component is marked to participate in native forms.

Details

The native equivalent of this meta tag is setting the static formAssociated property to true on the element's definition class. When writing form-associated elements, the provided internals variable allows for setting the internal form value (through .setFormValue()), setting its validity (using .setValidity()) and a whole range of other methods and properties. To learn more about ElementInternals, see ElementInternals on MDN.

Examples

Number input

Let's write a custom number input element. We'll use a regular <input> element (with type="text") for the input. Then, we'll expose its value through a value attribute with an accompanying .value property. When the text input by the user is not a number (i.e. converts to NaN), then we'll say the value is 0 and mark the input as invalid. Of course, to make it all work in <form> elements, we'll need to mark it with <meta form-associated>.

<title>number-input</title> <meta attribute="value" type="number"> <meta form-associated> <template mode="closed" delegates-focus="true"> <input type="text"> </template> <script> const input = query('input'); input.value = $.value; live.link($.$text, input); live.link($.$isValid, () => !isNaN($.text)); live.link($.$value, () => Number($.text) || 0); effect(() => { internals.setFormValue($.value); }); effect(() => { if($.isValid){ internals.setValidity({}); return; } const flags = { typeMismatch: true }; const message = 'Must be a number'; internals.setValidity(flags, message); }); </script>

Now, our <number-input> element may participate in forms, using the global name attribute. It will also respond to users attempting to submit an invalid value for the <number-input>. For component libraries, it's often a good idea to include properties exposed to native form controls, such as .form, .validity, and .willValidate, which may just be getters proxying the ElementInternals, and a .name property for the global name attribute.

See also