I have a custom element like this:
<my-magic-form>
#shadowRoot:
<form id="some_id_name_invisible_to_end_users">
<input disabled name="entry_id"></input>
<slot name="fields_toFill"></slot>
</form>
</my-magic-form>
The users of my widget are supposed to add their own input fields like this:
<my-magic-form>
<input slot="fields_toFill" value="some_value1"/>
<textarea slot="fields_toFill"/>
</my-magic-form>
My question is: how can I link those two slotted <input>
and <textarea>
controls to the <form>
element inside the shadow DOM of my widget? The end users are not required to know the inner form's id of my widget, so they cannot set the form
attribute when they author; and I've tried programmatically setting this attribute only to find out that this attribute is read-only!
A simple solution is to move the light DOM into the Shadow DOM content.
Listen to the slotchange
event then move the assignedNodes()
before the <slot>
element.
var form = this.shadowRoot.querySelector( 'form' )
var slot = this.shadowRoot.querySelector( 'slot' )
slot.addEventListener( 'slotchange', () => {
for (var field of slot.assignedNodes()) {
form.insertBefore( field, slot )
}
} )
Alternately, if you don't want to move the light DOM fields, you should duplicate them as <input type="hidden">
fields, for exemple whan the <form>
is submitted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With