Home > front end >  How to access to a store into array of stores? Using Svelte
How to access to a store into array of stores? Using Svelte

Time:07-02

I'm using svelte-forms and need to make an array of fields

field() returns a writable store and is a convenient function to create a new form input that will serve a your input controller.

Suppose the next scenario

<script lang="ts">
    let fields = [field("f1","f1",[]), field("f2","f1",[]);
</script>

{#each fields as field}
   {$field}
{/each}

How can i use the fields array to access to any field store?

CodePudding user response:

You can create a new top level scope by extracting the content of the each to a separate component. That way accessing the store will work as expected. E.g.

{#each fields as field}
   <Sub {field} />
{/each}
<!-- Sub.svelte -->
<script>
    export let field;
</script>

<input bind:value={$field.value} />

REPL example

  • Related