'how to bind svelte dynamic components values
Let's say I have this main App:
<script>
import Field from '../components/Field.svelte';
const components = {};
const fields = [
{
id: 'Check',
type: 'CheckBox',
value: false,
},
{
id: 'Text',
},
];
$: console.log(components);
</script>
<form>
{#each fields as item}
<Field {...item} bind:bind={components[item.bind]} bind:this={components[item.id]} />
{/each}
</form>
And I have two components, CheckBox and TextArea, both just implement HTML
inputs, and the Field Component is implemented like this:
<script>
import CheckBox from './CheckBox.svelte';
import TextArea from './TextArea.svelte';
export let attributes = {};
export let type = 'TextArea';
export let value = '';
export let id;
export let bind;
const fieldComponents = {
CheckBox: CheckBox,
TextArea: TextArea,
};
</script>
<svelte:component this={fieldComponents[type]} {bind} {id} {value} {attributes} />
That way I'm creating a dynamic form that has a checkbox and a textarea.
What I want is the "bind" attribute to be accessible from within the component, and to be able to bind the another component, That way i'll be able to achieve something like this:
<input type="checkbox" bind:checked={bind.value}>
which means that if the textarea will have text, the checkbox would be checked, if it's empty, the checkbox would be unchecked.
after all the components render i'm able to access them using the components
object because i'm binding them like this bind:this={components[item.id]}
but before they render I can't access them, is there a way to make it so one component can dynamically bind to the other?.
I demonstrated using only 2 component, it might as well be a large set of components.
The way I want to determine the binding is using a bind property inside the
fields array that matches the id of another field.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
