Skip to content

Instantly share code, notes, and snippets.

@mghdotdev
Created November 8, 2022 22:43
Show Gist options
  • Save mghdotdev/7dd5c7ffe5c71e21630a719a7de6f2cd to your computer and use it in GitHub Desktop.
Save mghdotdev/7dd5c7ffe5c71e21630a719a7de6f2cd to your computer and use it in GitHub Desktop.
Lit + FormProxy
import {FormProxy} from './form-proxy.js';
class MyComponent extends FormProxy(LitElement) {
render () {
return html`
<form>
<input type="text" />
</form>
`;
}
};
export const FormProxy = (superClass) => class extends superClass {
constructor () {
super();
this.outerForm = this.closest('form');
}
/**
* Get reference to the inner form element
*/
get innerForm () {
return this.shadowRoot.querySelector('form');
}
/**
* Create proxy on connected
*/
connectedCallback () {
super.connectedCallback();
this.outerFormProxy = document.createElement('div');
this.outerFormProxy.hidden = true;
this.outerForm.appendChild(this.outerFormProxy);
}
/**
* Delete proxy on disconnected
*/
disconnectedCallback () {
super.disconnectedCallback();
this.outerFormProxy.remove();
}
/**
* On 'updated' update the hidden form input
*/
updated () {
super.updated();
const formData = new FormData(this.innerForm);
let output = '';
for (const [key, value] of formData) {
output += `<input type="hidden" name="${key}" value="${value}" />`;
}
this.outerFormProxy.innerHTML = output;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment