'Using Svelte JS framework with a Web Component library, how can I accomplish two-binding with the custom elements via the bind:value directive?
Note: There is a GitHub issue open on the Svelte repo for this very question. https://github.com/sveltejs/svelte/issues/4838 While I understand that this may or may not someday become a feature of Svelte, what I am asking is how I can create a workaround today to support a third-party web component library like Shoelace or UI5, or Ionic with two-way binding?
Synopsis:
- I have set up a Svelte app and successfully added a Web Component Library (Ex: Shoelace).
- I write a line of code that uses two-way binding like:
<sl-input name="name" type="text" label="Name" bind:value={name}/>
- I cannot two-way bind (
bind:value={}
) because the Svelte compiler doesn't recognize the valid bindings for the custom web components.
If there were a wrapper library that you know of, or some other thing I could do to make it work, that would be great.
Solution 1:[1]
I am not sure if this will work with libraries but it is worth a shot. For my custom component I just followed this answer.
Add this in your custom component:
<script>
export let onValueChange;
export let value;
$: onValueChange(value);
</script>
And add this when using the component (it will give an error until you add this)
<custom-component onValueChange="{(x) => value = x}"/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Anders |