docs: add documentation on using the FormAssociated class
🙋 Documentation Request
As far as I can tell, the proper way to use the FormAssociated class in a FAST web component is to:
- add
import { FormAssociated } from "@microsoft/fast-foundation"; - change
extends FASTElementtoextends FormAssociated(FASTElement) - add the property
private internals: ElementInternals = this.elementInternals; - call
this.internals.setFormValue(initialValue);inconnectedCallbackto set the initial value - call
this.internals.setFormValue(newValue);every time the value changes
I tried all of this, but TypeScript doesn't like changes 2 and 3.
Where can I find an example of using the FormAssociated class or any documentation on it?
Agree @mvolkmann, we probably need better documentation here. To answer your question and give you an example in the interim, you might not need to extend FormAssociated...
On the Fluent side of things, we moved to extending FASTElement but setting static formAssociated = true on the form control elements. For example, our base BaseTextArea class:
https://github.com/microsoft/fluentui/blob/master/packages/web-components/src/textarea/textarea.base.ts
So that would update your instructions to:
- Add
static readonly formAssociated = true;to the class - Attach ElementInternals
public internals: ElementInternals = this.attachInternals(); - call
this.internals.setFormValue(initialValue); inconnectedCallbackto set the initial value - call
this.internals.setFormValue(newValue);every time the value changes
This should be all that's needed to get the custom element participating in forms.
Whether ElementInternals is public or private is up to you, we keep it public so we can access el.internals.role in our tests.
Would welcome a PR here from anyone interested!
@mvolkmann the one thing I'll call out is that @microsoft/fast-foundation has been deprecated and IMO the FormAssociated mixin was fairly out of date and a bit monolithic. With that said, @davatron5000's on point with the above. There are also ways to create "generic" classes for things which are nearly functionally the same and are form associated as has been done with Checkbox/Radio/Option in Fluent UI. Each of these extend a base class which includes the relevant consistent functionality for form association.
Thanks so much! The approach described by @davatron5000 worked perfectly for me.
The reason I asked the question is that I'm in the middle of writing a book on web components. It contains chapters on vanilla web components, Lit, Stencil, FAST, Solid, and wrec (my library). If anyone is interested in reviewing what I write about FAST, I'd be happy to share it before the book is published.