completefrontend
Open lab My progress
THE WEB COMPONENTS FIELD GUIDE

A base class for form controls

Write a web component form control base class: share ElementInternals with subclasses, pass attributes to an inner input, and test it in a real browser.

By the end, you can
  • 01
    Find the shared form codeList what every form control writes by hand, and see how the copies drift apart.
  • 02
    Write a form control base classShare the internals through a getter, answer the form's callbacks once, and let each control fill in its own hooks and pass-through list.
  • 03
    Test it in a real browserCheck FormData, reset, a disabled fieldset, validity, and restore, with @web/test-runner and @open-wc/testing.

What is a form control base class?

It's Friday at Leaf and Kettle, and orders come in fast. Meena's order form now has four pieces: a name box, the kit's gift message field, its oat milk switch, and its Place order button.

While an order is on its way, nobody should change it. So Meena adds one line that turns every control off. Asha presses Place order. Then she flips the oat milk switch, and it flips. Why does one line work on some controls and not on others?

A form control base class is one class that holds the form code every control needs. That's joining the form, the internals, the members a native input has, and the form's callbacks. Each control extends it, and adds only what makes it different. So every control answers a page the same way, as every native input does.

Here is Meena's form, with the kit from the last lesson. Press Place order:

An order form that turns every control off while it sendsPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><form>  <label>Name <input name="who" value="Asha"></label>  <tea-field name="message"><span slot="label">Gift message</span></tea-field>  <p><tea-toggle name="oat">Add oat milk</tea-toggle></p>  <tea-button>Place order</tea-button></form><script type="module">  import "./tea-kit/index.js";  const form = document.querySelector("form");  form.addEventListener("submit", (event) => {    event.preventDefault();    for (const control of form.elements) control.disabled = true;    for (const control of form.elements) console.log(control.localName, control.matches(":disabled") ? "off" : "still on");  });</script>
ResultLoading…
  • Line 3 is a native input. Lines 4 to 6 are the kit's field, switch, and button.
  • Line 13 sets disabled on every control in the form. Line 14 prints which ones really turned off.

It prints input off, tea-field still on, tea-toggle still on, and tea-button off. Each kit control was written by hand, one lesson at a time. The button got a disabled property in lesson 17.2. The switch and the field never did. So line 13 only stuck a new property on them, and nothing read it.

Real-life analogyThe same tin for every tea

Every tea at Leaf and Kettle goes into the same kind of tin. Each tin has the same lid, the same label, and the same seal that shows nobody opened it. Ravi doesn't design a new tin for each tea. Only the leaves inside change.

In real life: The shop's tin
In JavaScript: TeaFormControl, the base class
In real life: The lid, the label, and the seal
In JavaScript: Joining the form, the internals, and the native members
In real life: The leaves inside
In JavaScript: What's different: a checked state, a text box
In real life: A new tea in the same tin
In JavaScript: A new control that extends the base class
The main idea

Write the form code once. Put what every control needs in one base class. Each control extends it and fills in only its own value, rules, and look. Then a fix in the base class reaches every control.

A base class uses JavaScript's extends and super, from the inheritance lesson. The controls stay form-associated custom elements, from lesson 16.1. Those work in Chrome 77, Firefox 98, and Safari 16.4 and later.

What does every form-associated custom element repeat?

Start by counting. The kit has six form controls: the quantity, the blend, the search box, the switch, the button, and the field. Each one wrote its own form code. Here are the last five members of the switch, from kitAfter173's tea-kit/tea-toggle.js:

The end of the switch's class, before this lessonJavaScript
  /** The validity flags: valueMissing while it's required and off. */
  get validity() {
    return this.#internals.validity;
  }

  /** The message the form shows while the switch is invalid, or "". */
  get validationMessage() {
    return this.#internals.validationMessage;
  }

  /** Whether the form checks the switch: false while it's disabled. */
  get willValidate() {
    return this.#internals.willValidate;
  }

  /** Checks quietly. While it's invalid, fires invalid and returns false. */
  checkValidity() {
    return this.#internals.checkValidity();
  }

  /** Checks, and while it's invalid, shows the message at the switch and moves focus there. */
  reportValidity() {
    return this.#internals.reportValidity();
  }
  • Lines 2 to 4 give the validity flags. Lines 7 to 9 give the message.
  • Lines 12 to 14 say whether the form checks the switch.
  • Lines 17 to 19 and 22 to 24 are the two checks, the quiet one and the one that shows the message.

Each member just hands a job to the internals (MDN). The quantity, the blend, the search box, and the field end with the same code, word for word. Only the comments change.

That's one part. Read each row across: what a class writes, then which of the six controls write it.

What the kit's six form controls each write by hand
What the class writesWhich of the six controls write it
static formAssociated = true, and attachInternals() through the kit's list.All six write them.
The form and name getters.All six write them.
validity, validationMessage, willValidate, checkValidity(), and reportValidity().Five write them, word for word. The button has none.
A call to setFormValue() after each change.All six write one.
formResetCallback() and formStateRestoreCallback().Five write them. The button has neither.
formDisabledCallback(), to turn their inner parts off.Four write it: the quantity, the blend, the search box, and the field.
An invalid listener and a user-invalid state.Three write them: the quantity, the blend, and the field.
A disabled property.Only the button has one.
required and readOnly properties.None of them has these.
Keeping a property set before the kit loads.None of them does this.

Look at the last four rows. Copies drift. Each lesson added what it needed, so the controls now differ in small ways. The overview tripped over the disabled row. This page asks each control for seven members a native input has:

Which native members each control hasPop out in the code editor (opens in a new tab)HTML
<form>  <input name="tea">  <tea-quantity name="cups"></tea-quantity>  <tea-toggle name="oat">Oat milk</tea-toggle>  <tea-field name="note"><span slot="label">Note</span></tea-field>  <tea-button>Order</tea-button></form><script type="module">  import "./tea-kit/index.js";  const members = ["form", "name", "disabled", "required", "readOnly", "validity", "checkValidity"];  for (const control of document.forms[0].elements) {    const missing = members.filter((member) => !(member in control));    console.log(control.localName, missing.length ? `lacks ${missing.join(", ")}` : "has them all");  }</script>
ResultLoading…
  • Line 10 lists the seven members.
  • Line 12 keeps the ones a control lacks. member in control is true when the control has that member, on itself or its class.
  • Line 13 prints what's missing, or that it has them all.
  • input has them all
  • tea-quantity lacks disabled, required, readOnly
  • tea-toggle lacks disabled, required, readOnly
  • tea-field lacks disabled, required, readOnly
  • tea-button lacks required, readOnly, validity, checkValidity

The native input has all seven. Each kit control lacks a few, and not the same few. The HTML Standard gives every form-associated custom element the same four attributes: name, disabled, readonly, and form. They mean the same thing for every control. So one class can own them.

Two halves. Left, labelled kitAfter173: two crates, tea-toggle and tea-field, each holding a form code card and a card of its own, checked or count. Right, labelled kitAfter174: one crate, TeaFormControl, holds the form code card. Two smaller crates sit below it, tea-toggle with checked and tea-field with count. Each has an arrow up to TeaFormControl, labelled extends.kitAfter173form codecheckedtea-toggleform codecounttea-fieldkitAfter174form codeTeaFormControlcheckedtea-togglecounttea-fieldextends
Before, every control carries its own copy of the form code, and the copies drift apart. After, the form code sits once in TeaFormControl, and each control keeps only what's its own.

What a base class used to fake

Before every browser had internals, a base class had to pretend. The element-internals-polyfill shows how. Its setFormValue() adds a hidden input right after your element, with your name and value. The form finds that input and sends it. But the input sits in the page's own DOM, where page CSS and scripts can trip over it. Native internals hand the value to the form with nothing added. So the kit's base class needs no hidden inputs.

Why it matters: six copies of the same code drift into six slightly different controls. One copy can't.

How do you write a base class for form controls?

A base class is a class other classes extend. class TeaToggle extends TeaFormControl makes TeaFormControl the parent. The switch gets every member the parent has, and can replace any of them (overriding). Build it in three steps.

Step 1: move the shared members up

Here is a first version, form-control.js, with four of the shared members:

form-control.js: a first base classJavaScript
export class TeaFormControl extends HTMLElement {
  static formAssociated = true;
  #internals = this.attachInternals();

  get internals() {
    return this.#internals;
  }

  get form() {
    return this.#internals.form;
  }

  get name() {
    return this.getAttribute("name") ?? "";
  }

  get validity() {
    return this.#internals.validity;
  }

  checkValidity() {
    return this.#internals.checkValidity();
  }
}
  • Line 2 makes it form-associated.
  • Line 3 attaches the internals once, in a private field. Each kit control used to do this itself, as in lesson 16.1.
  • Lines 5 to 7 are a getter that hands the internals to subclasses. They can't reach the private field any other way.
  • Lines 9 to 23 are four shared members. name gives "" without the attribute, as a native input's does.

Here is a new control, TeaCups, that sends 3 cups. It extends the base class, and writes only its constructor:

Playground: how does a subclass reach the internals?
TeaCups, a control that extends the base classPop out in the code editor (opens in a new tab)HTML
<form>  <tea-cups name="cups"></tea-cups></form><script type="module">  import { TeaFormControl } from "./form-control.js";  class TeaCups extends TeaFormControl {    constructor() {      super();      this.internals.setFormValue("3");    }  }  customElements.define("tea-cups", TeaCups);  console.log("Sent:", new URLSearchParams(new FormData(document.forms[0])).toString() || "nothing");  console.log("formAssociated:", TeaCups.formAssociated, Object.hasOwn(TeaCups, "formAssociated"));</script>
ResultLoading…
Try it yourself
The getter hands TeaCups the internals

Line 9 reads this.internals, the base class's getter, and sends 3. TeaCups writes no formAssociated of its own, yet it's form-associated: define() found the parent's.

Only line 9 changes. The form-control.js tab is the first version above.
  • Line 6 makes TeaCups extend TeaFormControl.
  • Line 8 calls super(), which runs the parent's constructor and fields first (super in a constructor). Line 9 sends 3.
  • Line 13 prints what the form would send. Line 14 asks if TeaCups is form-associated, and if that flag is its own.

Through the getter, it prints Sent: cups=3, then formAssociated: true false. TeaCups wrote no static formAssociated. But customElements.define() reads it with a plain property lookup, and that lookup climbs the class chain to the parent. It finds the four form callbacks the same way, on the parent's prototype. So every control that extends the base class is form-associated.

Why can't a subclass use a #private field?

Now press the other two buttons:

  • A #private field. Line 9 writes this.#internals. The page throws SyntaxError: Private field '#internals' must be declared in an enclosing class, and nothing prints. A # name belongs only to the class that declares it (MDN). Not even a subclass can write it, as the private members lesson shows.
  • Attach again. Line 9 calls this.attachInternals() a second time. It throws NotSupportedError: the internals "were already attached". An element gets its internals once (MDN). So TeaCups never finishes building, and the form gets nothing.

So line 3 keeps the internals private, and lines 5 to 7 share them through a getter. JavaScript has no protected members, which a subclass could read and a page couldn't. The Web Components group discussed exactly this in issue 962. So the getter is public, and the kit's JSDoc and manifest mark it protected: for subclasses only.

Material Web names its getter with a Symbol, so code needs that symbol, imported from its file, to reach the internals. And the kit already lists every control's internals in globalThis._elementInternals, for checkers like axe (lesson 15.3). So the getter shares nothing new.

Real-life analogyOne key, cut once

The shop's cash box came with one key, and the locksmith won't cut a second. If Meena kept it in her own pocket, Ravi couldn't open the box on the evening shift. So she hangs it on a hook behind the counter, with a sign: staff only.

In real life: The cash box
In JavaScript: The element's internals
In real life: The locksmith cuts one key, never two
In JavaScript: attachInternals() works once
In real life: Meena's own pocket
In JavaScript: A #private field of the base class
In real life: The hook behind the counter, marked staff only
In JavaScript: The internals getter, marked protected

Step 2: let the base class answer the form

Each control also wrote its own form callbacks, from lesson 16.4. In kitAfter174, the base class answers them, and asks the control only for what's different. Here are its three callbacks, from tea-kit/form-control.js:

The base class's form callbacksJavaScript
  /** The form was reset: back to the start, with no error showing. */
  formResetCallback() {
    this.#tried = false;
    this.reset();
    this.changed();
  }

  /** Disabled by its own attribute or a <fieldset>: the inner element goes off too. The host's attribute is never touched. */
  formDisabledCallback(disabled) {
    if (this.inner) this.inner.disabled = disabled;
    this.changed();
  }

  /** The browser gives back the saved state, after Back. */
  formStateRestoreCallback(state) {
    this.restore(state);
    this.changed();
  }
  • Lines 2 to 6: on a reset, forget the failed send, call reset(), then changed().
  • Lines 9 to 12: when it's disabled or enabled, turn the inner element off or on, if there is one. The field's box is one. Then changed().
  • Lines 15 to 18: after Back, call restore() with the saved state, then changed().

The browser calls these at the right moments, as custom element reactions. reset() and restore() are hooks. A hook is a method the base class calls, and a subclass replaces with its own. Here is changed(), which every change goes through:

changed(): send, check, and drawJavaScript
  /** Hands the form the value and the state, checks the rules, and shows the error state once the form has tried to send. */
  changed() {
    this.#internals.setFormValue(this.formValue(), this.formState());
    const problem = this.validate();
    if (problem) this.#internals.setValidity(problem.flags, problem.message, problem.anchor);
    else this.#internals.setValidity({});
    const shown = this.#tried && this.#internals.willValidate && !this.#internals.validity.valid;
    if (shown) this.#internals.states.add("user-invalid");
    else this.#internals.states.delete("user-invalid");
    this.draw();
  }
  • Line 3 gives the form the value and the state from two more hooks, formValue() and formState(), as in lesson 16.2.
  • Lines 4 to 6 ask the validate() hook for the control's rules. It returns null, or the flags, message, and anchor for setValidity() (lesson 16.3).
  • Lines 7 to 9 add the user-invalid state once the form has tried to send, while the control is checked and invalid. That's lesson 16.3's state, now in one place.
  • Line 10 calls the draw() hook, so the control can update its own parts.

Each hook has a plain default in the base class. formValue() sends the value property, and restore() sets it. The others do nothing. Here are the switch's own hooks, from tea-kit/tea-toggle.js:

The switch's hooksJavaScript
  /** While it's on, the form sends the value. While it's off, nothing. */
  formValue() {
    return this.#checked ? this.value : null;
  }

  /** What Back brings back: "on" or "off". */
  formState() {
    return this.#checked ? "on" : "off";
  }

  /** Required and off: valueMissing, in the switch's own words. */
  validate() {
    if (this.#checked || !this.required) return null;
    return { flags: { valueMissing: true }, message: "Please turn this switch on." };
  }

  /** A reset: back where the checked attribute says, and the attribute leads again. */
  reset() {
    this.#dirty = false;
    this.#checked = this.defaultChecked;
  }

  /** After Back: on or off again, as the person left it. */
  restore(state) {
    this.checked = state === "on";
  }

  /** Shows on or off: the state for CSS, and the tree. */
  draw() {
    if (this.#checked) this.internals.states.add("checked");
    else this.internals.states.delete("checked");
    this.internals.ariaChecked = String(this.#checked);
  }
  • Line 3 sends the value while it's on, and nothing while it's off. Line 8 saves on or off for Back.
  • Lines 13 and 14: required and off is valueMissing, in the switch's own words.
  • Lines 19 and 20: a reset goes back to the checked attribute, which leads again (lesson 17.1). Line 25: Back flips it to what was saved.
  • Lines 30 to 32 draw the checked state, and tell the accessibility tree.

That's all of the switch's form code. The callbacks, the native members, and the error state come from the base class.

Two lanes. Left, TeaFormControl: a card formResetCallback(), and below it a card changed(). Right, TeaToggle: a card reset(), and below it, under the words its hooks, three cards: formValue(), validate(), and draw(). Arrows go from formResetCallback() to reset(), from reset() back to changed(), and from changed() to each of the three hooks.TeaFormControlTeaToggleformResetCallback()reset()changed()formValue()validate()draw()its hooks
When the form resets, the browser calls the base class. TeaFormControl calls the switch's reset(), then changed() asks the switch for its value and its rules, and lets it draw.
Real-life analogyA brewing card with blanks

Meena prints one brewing card for the whole shop. It says: heat the water to a blank, steep for a blank, then pour. Each tea's card fills in the blanks. Ravi follows the same steps for every tea, and reads the blanks as he goes.

In real life: The printed steps
In JavaScript: The callbacks and changed(), in the base class
In real life: A blank on the card
In JavaScript: A hook, like validate()
In real life: Each tea's filled-in card
In JavaScript: A control's own hooks
In real life: Ravi following the card
In JavaScript: The browser calling the callbacks

Watch the base class call two hooks. LoudToggle extends the kit's switch, and prints when they run:

A switch that prints when its hooks runPop out in the code editor (opens in a new tab)HTML
<form>  <loud-toggle name="oat" required>Add oat milk</loud-toggle>  <button type="reset">Clear</button></form><button id="check">Check</button><script type="module">  import { TeaToggle } from "./tea-kit/tea-toggle.js";  class LoudToggle extends TeaToggle {    reset() {      console.log("reset()");      super.reset();    }    validate() {      console.log("validate()");      return super.validate();    }  }  customElements.define("loud-toggle", LoudToggle);  document.querySelector("#check").addEventListener("click", () => console.log("valid:", document.forms[0].checkValidity()));</script>
ResultLoading…
  • Line 8 adds a third class to the chain.
  • Lines 9 to 12 print, then call the switch's own reset() with super.reset(). Lines 13 to 16 do the same for validate().
  • Line 19: Check asks the form to check itself, and prints the answer.
  1. As the page loads, it prints validate(). The required attribute arrived, so the base class checked again.
  2. Press Check: validate(), then valid: false. The invalid event reached the base class, which checked again before the page printed.
  3. Click the switch: validate(). Press Clear: reset(), then validate().

No line of LoudToggle calls its own hooks. The base class does. One rule keeps that safe: the base class never calls a hook from its constructor. A subclass's fields are added only after super() returns. A hook that read #checked that early would throw a TypeError.

Step 3: pick up properties set too early

Lesson 4.2 found a trap. A property set before the kit loads lands on the element itself, and hides the setter. Lesson 4.2 fixed it in each class. Now the base class does it once:

The upgrade-property pattern, in the base classJavaScript
  /** A property set before the kit loaded hides its setter: hand each one to the setter, as lesson 4.2 does. */
  connectedCallback() {
    for (const name of this.constructor.setters) {
      if (!Object.hasOwn(this, name)) continue;
      const value = this[name];
      delete this[name];
      this[name] = value;
    }
  }
  • Line 3 goes through a list, setters. The base class lists name, disabled, required, and readOnly. The switch adds checked, defaultChecked, and value.
  • Line 4 skips a name the element doesn't own. Object.hasOwn() checks the element itself, not its class.
  • Lines 5 to 7 read the value, delete the own property, and set it again, through the setter.

Try a page that sets the field's value before the kit loads:

Playground: a value set before the kit loads
A gift message set before the kit loadsPop out in the code editor (opens in a new tab)HTML
<form>  <tea-field name="message"><span slot="label">Gift message</span></tea-field></form><script type="module">  const field = document.querySelector("tea-field");  field.value = "Happy birthday";  await import("./tea-kit/index.js");  const sent = new FormData(field.form).get("message");  console.log(`value: ${field.value}, sent: "${sent}"`);</script>
ResultLoading…
Try it yourself
The early value hides the setter

Line 6 runs before the kit loads, so value becomes the element's own property. The field's setter never runs: the box stays empty, and the form sends "".

Only the kit changes: kitAfter173, or kitAfter174 with the base class.
  • Line 6 sets the value before line 7 loads the kit.
  • Line 9 prints the value, and what the form would send.
  • kitAfter173: value: Happy birthday, sent: "". The box is empty.
  • kitAfter174: value: Happy birthday, sent: "Happy birthday". The box shows it too.

Why it matters: frameworks and scripts set properties whenever they like. With the base class, every control keeps them.

How do you pass attributes through to an inner input?

Lesson 16.5's search box and lesson 17.3's field wrap a real input. Some attributes on the tag must reach it. Here is how kitAfter173's field did it, by hand:

The field's attributes, forwarded by handJavaScript
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === "value" && !this.#dirty) this.#box.value = newValue ?? "";
    if (name === "readonly") this.#box.readOnly = newValue !== null;
    if (name === "placeholder" || name === "autocomplete") {
      if (newValue === null) this.#box.removeAttribute(name);
      else this.#box.setAttribute(name, newValue);
    }
    this.#update();
  }
  • Line 3 copies readonly onto the box. Lines 4 to 7 copy placeholder and autocomplete.
  • Every new attribute needs another line, in every control that wraps an input.

A base class can do this from a list. Here are two statics at the top of form-control.js:

The pass-through list, and the observed attributesJavaScript
  static passThrough = [];
  static setters = ["name", "disabled", "required", "readOnly"];

  static get observedAttributes() {
    return [...new Set(["required", "readonly", ...this.passThrough])];
  }
  • Line 1 is the list. It's empty in the base class, and each subclass gives its own.
  • Lines 4 to 6 are the observed attributes. They're a getter, so this is the subclass when define() reads them. So line 5 adds the subclass's list. A Set drops a name listed twice.

Then one callback copies each attribute on the list:

Copying the attributes on the listJavaScript
  attributeChangedCallback(name, oldValue, newValue) {
    const inner = this.inner;
    if (inner && this.constructor.passThrough.includes(name)) {
      if (newValue === null) inner.removeAttribute(name);
      else inner.setAttribute(name, newValue);
    }
    this.changed();
  }
  • Line 2 asks for the inner element, through another getter. It's null in the base class.
  • Line 3 goes on only for a name on the list. Lines 4 and 5 remove or copy the attribute, as the field did by hand.
  • Line 7 calls changed() for every observed attribute, so a new required is checked at once.

Now the field writes only its list, and which element is its box:

The start of the field's classJavaScript
export class TeaField extends TeaFormControl {
  static passThrough = ["placeholder", "autocomplete", "readonly"];
  static setters = [...super.setters, "value", "defaultValue"];

  static get observedAttributes() {
    return [...super.observedAttributes, "value", "maxlength", "required-message"];
  }
  • Line 2 is the list. Line 3 adds value and defaultValue to the parent's setters with super.setters.
  • Line 6 adds the field's own observed attributes after the parent's, with super.observedAttributes.
The field's inner elementJavaScript
  /** The text box: the base class passes placeholder, autocomplete, and readonly on to it, and turns it off with the field. */
  get inner() {
    return this.#box;
  }

Line 3 hands the base class the box. That's all the field writes for passing attributes through.

Properties come into it too. A boolean attribute is reflected when a property reads and writes it: the attribute is there or not, and the property is true or false (MDN). The base class reflects disabled, required, and readOnly. Each getter calls hasAttribute(), and each setter calls toggleAttribute(). So field.readOnly = true adds readonly to the tag, and the list carries it to the box:

readOnly and placeholder reach the boxPop out in the code editor (opens in a new tab)HTML
<form>  <tea-field name="tea" placeholder="Try jasmine"><span slot="label">Tea</span></tea-field></form><script type="module">  import "./tea-kit/index.js";  const field = document.querySelector("tea-field");  const box = field.shadowRoot.querySelector("input");  console.log("box:", box.placeholder, box.readOnly);  field.setAttribute("placeholder", "Try oolong");  field.readOnly = true;  console.log("tag:", field.outerHTML.slice(0, field.outerHTML.indexOf(">") + 1));  console.log("box:", box.placeholder, box.readOnly);</script>
ResultLoading…
  • Line 8 prints the box at the start. Line 9 changes the placeholder, and line 10 sets readOnly.
  • Line 11 prints the start of the tag. Line 12 prints the box again.
  • box: Try jasmine false
  • tag: <tea-field name="tea" placeholder="Try oolong" readonly="">
  • box: Try oolong true

disabled isn't on the list. A disabled fieldset turns its controls off, but adds no attribute to them (lesson 16.4). A copied attribute would miss it. So the base class turns the inner element off in formDisabledCallback(), which runs either way:

A field inside a disabled fieldsetPop out in the code editor (opens in a new tab)HTML
<form>  <fieldset disabled>    <tea-field name="tea" value="Sencha"><span slot="label">Tea</span></tea-field>  </fieldset></form><script type="module">  import "./tea-kit/index.js";  const field = document.querySelector("tea-field");  const box = field.shadowRoot.querySelector("input");  console.log(`disabled: ${field.disabled}, :disabled: ${field.matches(":disabled")}, box: ${box.disabled}`);  console.log("sent:", [...new FormData(field.form)].length, "entries");</script>
ResultLoading…

Line 10 prints disabled: false, :disabled: true, box: true. The tag has no attribute, so the property is false, as on a native input. But :disabled matches, and the box is off. Line 11 prints sent: 0 entries: a disabled control sends nothing.

Two columns. Left, readonly: a card field.readOnly = true, an arrow labelled sets to a card tea-field readonly, and an arrow labelled copies to a card input readonly. Right, disabled: a card fieldset disabled, an arrow labelled calls to a card formDisabledCallback(true), and an arrow labelled sets to a card box.disabled = true. Under the right column: the tag gets no attribute.readonlyfield.readOnly = truesets<tea-field readonly>copies<input readonly>disabled<fieldset disabled>callsformDisabledCallback(true)setsbox.disabled = truethe tag gets no attribute
A property writes the tag's attribute, and the base class copies it to the box. A disabled fieldset adds no attribute, so the box goes off through formDisabledCallback().
Real-life analogyThe counter and the kitchen hatch

At a café, you tell the person at the counter: no sugar, oat milk. They write it on a slip and pass it through the hatch to the kitchen, which makes the drink. You never talk to the kitchen yourself. And some things stay at the counter, like paying.

In real life: The counter
In JavaScript: The tag
In real life: The kitchen
In JavaScript: The inner input
In real life: The order slip through the hatch
In JavaScript: An attribute copied to the input
In real life: The things the slip has room for
In JavaScript: The passThrough list
In real life: Paying, which stays at the counter
In JavaScript: name and value, which the tag keeps

Read each row across: an attribute on the tag, whether it goes on to the box, and why.

Which of the field's attributes go on to its box
Attribute on the tagDoes it go on to the box?Why
placeholderYes, through the list.The box shows it, so the box needs it.
autocompleteYes, through the list.The browser's autofill reads it on the box.
readonlyYes, through the list.It stops typing in the box. The readOnly property writes it.
disabledNo. formDisabledCallback() turns the box off.A disabled fieldset adds no attribute, so a copy would miss it.
requiredNo.The field checks itself, in its own words.
maxlengthNo.On a box, it cuts what people paste, as lesson 17.3 showed.
nameNo.The tag joins the form. A box in a shadow root never does.
valueNo. The field copies it in until someone types.It's where the text starts, not the text now.

A page may also want field.placeholder as a property, as an input has. A later lesson, Declaring attributes, makes properties like that from a list.

Should you use a base class or a mixin?

A chain of classes is easy to read while it's short. It gets stiff as it grows:

  • A class has only one parent. A control that must extend a library's class, like Lit's in stage 8, can't also extend TeaFormControl.
  • Each class must call super in every callback it replaces. Miss one, and the classes above it never hear about the change. Exercise 4 shows it.
  • A change near the top reaches every control below, whether it fits them or not.

A mixin is the other shape. Lit's docs call mixins subclass factories: a function that takes a class, and returns a subclass of it with more members. Here is the start of the base class as a mixin:

form-control-mixin.js: the same start, as a mixinJavaScript
export const FormControl = (Base) =>
  class FormControlElement extends Base {
    static formAssociated = true;
    #internals = this.attachInternals();

    get internals() {
      return this.#internals;
    }

    get form() {
      return this.#internals.form;
    }
  };
  • Line 1 takes Base, the parent to build on.
  • Line 2 returns a new class that extends it, FormControlElement.
  • Lines 3 to 12 are the first version's start, unchanged.

The kit's badge already has a parent and a look of its own. The mixin puts form code on top:

The badge becomes a form control through the mixinPop out in the code editor (opens in a new tab)HTML
<form>  <tea-cups name="cups">3 cups</tea-cups></form><script type="module">  import { FormControl } from "./form-control-mixin.js";  import { TeaBadge } from "./tea-kit/tea-badge.js";  class TeaCups extends FormControl(TeaBadge) {    constructor() {      super();      this.internals.setFormValue("3");    }  }  customElements.define("tea-cups", TeaCups);  const chain = [];  for (let step = TeaCups; step !== HTMLElement; step = Object.getPrototypeOf(step)) chain.push(step.name);  console.log([...chain, "HTMLElement"].join(" extends "));  console.log("Sent:", new URLSearchParams(new FormData(document.forms[0])).toString());</script>
ResultLoading…
  • Line 7 passes TeaBadge to the mixin, and extends what comes back.
  • Lines 14 to 16 walk up the chain and print each class's name. Line 17 prints what the form would send.

It prints TeaCups extends FormControlElement extends TeaBadge extends HTMLElement, then Sent: cups=3. The badge keeps its look, and joins the form. A mixin is like a seal you can press onto any tin, where a base class is the tin itself.

Read across: how each shape answers four questions.

A base class and a mixin, side by side
QuestionA base classA mixin
How does a control get the code?It extends the class: class TeaToggle extends TeaFormControl.It passes its parent to a function: class TeaCups extends FormControl(TeaBadge).
Can the control keep another parent?No. A class has only one parent.Yes. The mixin goes on top of any parent.
What must every override do?Call the parent's method with super.The same: call the method with super.
Who uses it for forms?Web Awesome's form controls.Material Web's form controls.

Both shapes ship real form controls. Material Web builds its controls from mixins, like mixinFormAssociated(). Web Awesome uses a base class, WebAwesomeFormAssociatedElement. The kit keeps one base class: its controls all extend HTMLElement, and the chain is short. The JavaScript course's mixins lesson shows the pattern in plain JavaScript.

How do you test form-associated custom elements?

The base class now holds code six controls will depend on. A mistake there breaks them all. So test it, in a real browser. A form's work, like collecting FormData or resetting, is the browser's own code. Here is what jsdom, a fake page that many Node test tools use, gives a form control:

A form control's internals in jsdom, run in NodeJavaScript
import { JSDOM } from "jsdom";

const { window } = new JSDOM('<form><tea-cups name="cups"></tea-cups></form>', { runScripts: "outside-only" });
window.eval(`customElements.define("tea-cups", class extends HTMLElement {
  static formAssociated = true;
  internals = this.attachInternals();
});`);
const { internals } = window.document.querySelector("tea-cups");
console.log(typeof internals.setFormValue, typeof internals.setValidity, internals.form);
  • Line 3 makes a fake page with a form. Lines 4 to 7 define a form-associated tea-cups in it.
  • Line 9 prints three of the internals' form parts.

In Node, it prints undefined undefined undefined. jsdom's internals have no setFormValue(), no setValidity(), and no form. A test there would never see the form at all.

Real-life analogyTasting every tea before the shop opens

Each morning, Ravi brews one cup of every tea and tastes it. He uses the real kettle and the real water, because the recipe can't tell him the water is too hard today. He checks the same things for each tea: the color, the smell, and the taste.

In real life: Brewing with the real kettle
In JavaScript: Testing in a real browser
In real life: Reading the recipe instead
In JavaScript: Testing in a fake page, like jsdom
In real life: The same checks for every tea
In JavaScript: The same test plan for every control

Here's the test plan. Put the control in a form, then check five things the browser does:

  1. FormData holds the value under the control's name.
  2. A reset brings back where it started.
  3. Inside a disabled fieldset, it matches :disabled, and FormData leaves it out.
  4. Required and empty, its validity says valueMissing, and the form won't pass a check.
  5. After Back, it takes back the saved state. No test can press Back, so call formStateRestoreCallback() yourself, as the browser would.

Here is the plan for the field, as a test file for @web/test-runner, version 1, with @open-wc/testing, version 5:

test/tea-field.test.js, for @web/test-runner and @open-wc/testingJavaScript
import { expect, fixture } from "@open-wc/testing";
import "../tea-kit/index.js";

describe("tea-field", () => {
  it("sends its text under its name", async () => {
    const form = await fixture('<form><tea-field name="who" value="Asha"></tea-field></form>');
    expect(new FormData(form).get("who")).to.equal("Asha");
  });

  it("goes back to its value attribute on reset", async () => {
    const form = await fixture('<form><tea-field name="who" value="Asha"></tea-field></form>');
    form.elements.who.value = "Ravi";
    form.reset();
    expect(form.elements.who.value).to.equal("Asha");
  });

  it("is left out in a disabled fieldset", async () => {
    const form = await fixture('<form><fieldset disabled><tea-field name="who" value="Asha"></tea-field></fieldset></form>');
    expect(form.elements.who.matches(":disabled")).to.be.true;
    expect(new FormData(form).has("who")).to.be.false;
  });

  it("is missing a value while required and empty", async () => {
    const form = await fixture('<form><tea-field name="who" required></tea-field></form>');
    expect(form.elements.who.validity.valueMissing).to.be.true;
    expect(form.checkValidity()).to.be.false;
  });

  it("takes back the text the browser restores", async () => {
    const form = await fixture('<form><tea-field name="who"></tea-field></form>');
    form.elements.who.formStateRestoreCallback("Ravi", "restore");
    expect(new FormData(form).get("who")).to.equal("Ravi");
  });
});
  • Line 1 imports expect() and fixture(). describe() and it() come from Mocha, the test runner's default.
  • Line 6: fixture() puts the markup in the page, waits for it, and returns the form. It removes it after each test.
  • Line 7: expect() is chai's. The test fails unless the value equals Asha.
  • Lines 12 to 14 change, reset, and check. Lines 19 and 20 check the fieldset, and lines 25 and 26 required.
  • Line 31 plays the browser's part after Back.

Install the two packages, and run the tests:

Install and run @web/test-runnerShell
npm install --save-dev @web/test-runner @open-wc/testing
npx web-test-runner "test/**/*.test.js" --node-resolve

Line 1 installs the two packages for development. Line 2 runs every file in test that ends in .test.js. By default, it runs them in the Chrome on your computer. With @web/test-runner-playwright, it runs them in Chromium, Firefox, and WebKit (browser launchers).

The same checks also run right here. The Result can't install packages, so its mini-test.js tab is a small stand-in for describe(), it(), expect(), and fixture(). The checks are the same lines:

Playground: run the field's tests
The field's five checks, in the pagePop out in the code editor (opens in a new tab)HTML
<script type="module">  import { describe, expect, fixture, it, run } from "./mini-test.js";  import "./tea-kit/index.js";   describe("tea-field", () => {    it("sends its text under its name", async () => {      const form = await fixture('<form><tea-field name="who" value="Asha"></tea-field></form>');      expect(new FormData(form).get("who")).to.equal("Asha");    });     it("goes back to its value attribute on reset", async () => {      const form = await fixture('<form><tea-field name="who" value="Asha"></tea-field></form>');      form.elements.who.value = "Ravi";      form.reset();      expect(form.elements.who.value).to.equal("Asha");    });     it("is left out in a disabled fieldset", async () => {      const form = await fixture('<form><fieldset disabled><tea-field name="who" value="Asha"></tea-field></fieldset></form>');      expect(form.elements.who.matches(":disabled")).to.be.true;      expect(new FormData(form).has("who")).to.be.false;    });     it("is missing a value while required and empty", async () => {      const form = await fixture('<form><tea-field name="who" required></tea-field></form>');      expect(form.elements.who.validity.valueMissing).to.be.true;      expect(form.checkValidity()).to.be.false;    });     it("takes back the text the browser restores", async () => {      const form = await fixture('<form><tea-field name="who"></tea-field></form>');      form.elements.who.formStateRestoreCallback("Ravi", "restore");      expect(new FormData(form).get("who")).to.equal("Ravi");    });  });   run();</script>
ResultLoading…
Try it yourself
Five checks, five passes

Each check builds a form in the page, does one thing a person or the browser does, and compares what the form holds with what it should hold.

Only the tea-kit/tea-field.js tab changes. Line 2 imports the stand-in, and line 37 starts the checks.
  • The kit's field prints five lines, each starting with ok.
  • A field that forgot reset() prints not ok - tea-field goes back to its value attribute on reset: expected "Ravi" to equal "Asha". The other four still pass.

A failing check names what it found, so the fix is clear. To test the base class itself, run the same plan through every control that extends it. Exercise 6 writes the switch's. open-wc's defineCE() helps too: it defines a throwaway subclass under a fresh tag name, so a test can try the base class with a control of its own.

Moving the kit's controls onto the base class

kitAfter174 adds the base class to the kit, as tea-kit/form-control.js. The switch and the field now extend it. Here is Meena's form again, with both kits:

Playground: the overview's form, before and after
An order form that turns every control off while it sendsPop out in the code editor (opens in a new tab)HTML
<link rel="stylesheet" href="tea-kit/tokens.css"><form>  <label>Name <input name="who" value="Asha"></label>  <tea-field name="message"><span slot="label">Gift message</span></tea-field>  <p><tea-toggle name="oat">Add oat milk</tea-toggle></p>  <tea-button>Place order</tea-button></form><script type="module">  import "./tea-kit/index.js";  const form = document.querySelector("form");  form.addEventListener("submit", (event) => {    event.preventDefault();    for (const control of form.elements) control.disabled = true;    for (const control of form.elements) console.log(control.localName, control.matches(":disabled") ? "off" : "still on");  });</script>
ResultLoading…
Try it yourself
Two controls ignore disabled

The switch and the field have no disabled property, so line 13 only gives each one a property of its own. Nothing reads it, and they stay on.

Only the kit changes. Press Place order.

With kitAfter174, it prints input off, tea-field off, tea-toggle off, and tea-button off. Asha can't flip the switch while her order is on its way.

Here is the middle of the field's class now, from tea-kit/tea-field.js:

The field's own form code, on the base classJavaScript
  attributeChangedCallback(name, oldValue, newValue) {
    if (name === "value" && !this.#dirty) this.#box.value = newValue ?? "";
    super.attributeChangedCallback(name, oldValue, newValue);
  }

  /** Required and empty, or longer than maxlength: the rule, in the field's words, at the box. */
  validate() {
    const text = this.#box.value;
    const max = this.#max();
    if (this.required && text === "") {
      return { flags: { valueMissing: true }, message: this.getAttribute("required-message") ?? fillIn, anchor: this.#box };
    }
    if (max !== null && text.length > max) {
      return { flags: { tooLong: true }, message: `Use ${max} characters or less.`, anchor: this.#box };
    }
    return null;
  }

  /** A reset: back to the value attribute, which leads again. */
  reset() {
    this.#dirty = false;
    this.#box.value = this.defaultValue;
  }
  • Line 2 copies the value attribute into the box until someone types. Line 3 hands over to the parent.
  • Lines 7 to 17 are lesson 17.3's two rules, in the field's own words, with the box as the anchor (validation messages).
  • Lines 20 to 23 bring back the value attribute on a reset.

Its draw() writes the count and the error. Everything else comes from the base class. Here is the member check from the start of the lesson, with the new kit:

Which native members each control has, with kitAfter174Pop out in the code editor (opens in a new tab)HTML
<form>  <input name="tea">  <tea-quantity name="cups"></tea-quantity>  <tea-toggle name="oat">Oat milk</tea-toggle>  <tea-field name="note"><span slot="label">Note</span></tea-field>  <tea-button>Order</tea-button></form><script type="module">  import "./tea-kit/index.js";  const members = ["form", "name", "disabled", "required", "readOnly", "validity", "checkValidity"];  for (const control of document.forms[0].elements) {    const missing = members.filter((member) => !(member in control));    console.log(control.localName, missing.length ? `lacks ${missing.join(", ")}` : "has them all");  }</script>
ResultLoading…

It's the same page. Line 13 now prints tea-toggle has them all and tea-field has them all. The quantity and the button print what they printed before.

Pages see a few new things:

  • Both controls have disabled, required, and readOnly properties, and keep properties set before the kit loads.
  • name gives "" without the attribute, as an input's does. It used to give null.
  • The switch gets the user-invalid state. The field gets defaultValue, and its error hides while it's disabled or readonly.

The course's test runs pages from lessons 13.2, 14.1, 15.1, 15.2, 15.3, 16.5, 17.1, 17.2, and 17.3 with kitAfter173 and kitAfter174. Every printed line, box, color, and tree stays the same. The JSDoc and custom-elements.json document the base class, with its hooks marked protected. The quantity, the blend, the search box, and the button keep their own copies for now. Each can move over the same way, with the same test plan.

Why it matters: the next control the kit gets starts with the form code done, and tested.

Common mix-ups

  • "A subclass can use its parent's #internals." No. A # name belongs only to the class that declares it. The subclass's script doesn't even parse.
  • "Each subclass can call attachInternals() for itself." No. It works once per element. The second call throws NotSupportedError.
  • "Every subclass must write static formAssociated = true." No. define() finds the parent's through the class chain.
  • "A subclass's observedAttributes adds to its parent's." No. It replaces them. Build on super.observedAttributes.
  • "Copy disabled to the inner input, like placeholder." No. A disabled fieldset adds no attribute. Turn the input off in formDisabledCallback().
  • "A base class can call its hooks from its constructor." No. The subclass's fields don't exist yet, so reading one throws a TypeError.
  • "The polyfill's hidden input works the same as native internals." No. It puts an input in the page's DOM. Native internals add nothing.
  • "Form controls can be tested in jsdom." No. Its internals have no setFormValue(), form, or setValidity().
  • "A deeper chain shares more code." No. Each layer adds super calls that must all be right, and a class can have only one parent. Mixins can combine behavior instead.

Practice exercises

Exercise 1 · Warm-upA subclass that says no

Line 7 sets formAssociated to false. Predict what the page prints, then run it.

<form>
  <tea-cups name="cups"></tea-cups>
</form>
<script type="module">
  import { TeaFormControl } from "./form-control.js";
  class TeaCups extends TeaFormControl {
    static formAssociated = false;
    constructor() {
      super();
      this.internals.setFormValue("3");
    }
  }
  customElements.define("tea-cups", TeaCups);
  console.log("Sent:", new URLSearchParams(new FormData(document.forms[0])).toString() || "nothing");
</script>

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upWhose observed attributes?

    Line 14 makes the control required. Predict what line 15 prints, then run it.

    <form>
      <tea-cups name="cups"></tea-cups>
    </form>
    <script type="module">
      import { TeaFormControl } from "./tea-kit/form-control.js";
      class TeaCups extends TeaFormControl {
        static observedAttributes = ["flavor"];
        validate() {
          return this.required ? { flags: { valueMissing: true }, message: "Pick a number of cups." } : null;
        }
      }
      customElements.define("tea-cups", TeaCups);
      const cups = document.querySelector("tea-cups");
      cups.required = true;
      console.log("valid:", cups.validity.valid);
    </script>

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticePass one more attribute through

      Make line 7 pass inputmode on to the box. What does the page print then?

      <form>  <tea-cups name="cups"><span slot="label">Cups</span></tea-cups></form><script type="module">  import { TeaField } from "./tea-kit/tea-field.js";  class TeaCups extends TeaField {    // Pass inputmode on to the box here.  }  customElements.define("tea-cups", TeaCups);  const cups = document.querySelector("tea-cups");  cups.setAttribute("inputmode", "numeric");  console.log("inputmode:", cups.shadowRoot.querySelector("input").inputMode || "none");</script>
      ResultLoading…

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeFind the missing super

        The box shows no placeholder. Fix line 9. What does the page's last line print then?

        <form>  <tea-note name="note" placeholder="No sugar"><span slot="label">Note</span></tea-note></form><script type="module">  import { TeaField } from "./tea-kit/tea-field.js";  class TeaNote extends TeaField {    attributeChangedCallback(name, oldValue, newValue) {      if (name === "placeholder") console.log("placeholder changed");      // The base class never hears about the change.    }  }  customElements.define("tea-note", TeaNote);  const box = document.querySelector("tea-note").shadowRoot.querySelector("input");  console.log("box placeholder:", box.placeholder || "none");</script>
        ResultLoading…

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeWrite a validate() hook

          Replace line 15 with a validate() hook: fewer than 1 cup is rangeUnderflow, with the words Pick 1 or more. What does the page print?

          <form>  <tea-cups name="cups"></tea-cups></form><script type="module">  import { TeaFormControl } from "./tea-kit/form-control.js";  class TeaCups extends TeaFormControl {    #cups = 0;    get value() {      return String(this.#cups);    }    set value(cups) {      this.#cups = Number(cups);      this.changed();    }    // Write validate() here: fewer than 1 cup is rangeUnderflow, "Pick 1 or more."  }  customElements.define("tea-cups", TeaCups);  const cups = document.querySelector("tea-cups");  cups.value = 0;  console.log(cups.checkValidity(), cups.validationMessage || "no message");</script>
          ResultLoading…

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeTest the switch in a disabled fieldset

            The page checks the switch four ways. Replace line 29 with a fifth check, named is left out in a disabled fieldset. What does it print?

            <script type="module">  import { describe, expect, fixture, it, run } from "./mini-test.js";  import "./tea-kit/index.js";   describe("tea-toggle", () => {    it("sends on while it's on", async () => {      const form = await fixture('<form><tea-toggle name="oat" checked>Oat milk</tea-toggle></form>');      expect(new FormData(form).get("oat")).to.equal("on");    });     it("goes back to its checked attribute on reset", async () => {      const form = await fixture('<form><tea-toggle name="oat" checked>Oat milk</tea-toggle></form>');      form.elements.oat.click();      form.reset();      expect(form.elements.oat.checked).to.be.true;    });     it("is missing a value while required and off", async () => {      const form = await fixture('<form><tea-toggle name="oat" required>Oat milk</tea-toggle></form>');      expect(form.elements.oat.validity.valueMissing).to.be.true;    });     it("takes back the state the browser restores", async () => {      const form = await fixture('<form><tea-toggle name="oat">Oat milk</tea-toggle></form>');      form.elements.oat.formStateRestoreCallback("on", "restore");      expect(new FormData(form).get("oat")).to.equal("on");    });     // Check that a disabled fieldset leaves it out.  });   run();</script>
            ResultLoading…

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              The form control base class quiz · 8 questionsScore: first tries count
              1. Question 1 of 8What does this class chain print in Chrome?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                class TeaFormControl extends HTMLElement {
                  static formAssociated = true;
                }
                class TeaCups extends TeaFormControl {}
                console.log(TeaCups.formAssociated, Object.hasOwn(TeaCups, "formAssociated"));

                Choose an answer to see the explanation.

              2. Question 2 of 8A subclass's constructor writes this.#internals, a field only its base class declares. What happens?

                Choose an answer to see the explanation.

              3. Question 3 of 8A subclass calls this.attachInternals() after super(), and the base class already called it. What happens?

                Choose an answer to see the explanation.

              4. Question 4 of 8A subclass writes static observedAttributes = ["checked"]. Its base class's getter listed required. What happens when a page sets required?

                Choose an answer to see the explanation.

              5. Question 5 of 8Why does the base class turn the inner box off in formDisabledCallback(), instead of copying the disabled attribute?

                Choose an answer to see the explanation.

              6. Question 6 of 8Why should a base class never call a hook like formValue() from its own constructor?

                Choose an answer to see the explanation.

              7. Question 7 of 8Why run a form control's tests in a real browser?

                Choose an answer to see the explanation.

              8. Question 8 of 8When is a mixin a better fit than a base class?

                Choose an answer to see the explanation.

              Key takeaways

              • Form controls written one by one repeat the same code: joining the form, the internals, the native members, and the callbacks. The copies drift apart.
              • A base class holds that code once. define() finds its static formAssociated and its callbacks through the class chain.
              • Attach the internals once, in the base class, and share them through a getter. A subclass can't name a #private field, and a second attachInternals() throws.
              • Let the base class answer the form and call hooks: formValue(), formState(), validate(), reset(), restore(), and draw(). Never call a hook from the constructor.
              • Run lesson 4.2's upgrade pattern once, for every property in a setters list.
              • Pass attributes to the inner input from a list. Turn it off in formDisabledCallback(), because a fieldset adds no attribute.
              • A mixin puts the same code on any parent class. A base class is simpler while the chain is short.
              • Test in a real browser: FormData, reset, a disabled fieldset, validity, and restore, for every control that extends the base class.

              Remember the one-liner.
              A form control base class writes the form code once. Each control extends it and fills in only its own value, rules, and look.

              Sources

              The facts on this page come from these standards, docs, source files, and discussions:

              Support data comes from MDN's browser-compat-data.

              Coming next: Reactive properties, the first lesson of Building components well. It draws a component again when a property changes, and batches many changes into one update.

              CompleteFrontend Clear concepts. Working examples.