visual2k
visual2k

Reputation: 55

Svelte set bind:value from #each Key

I am trying to bind values to a Each Value:

For example:

JS:

let test = ""
let headers = [
    {
      title: "test",
      connected: test,
    }
]

const setPage = () => {
    console.log(test);
  };

HTML:

{#each headers as header}
<input
 type="text"
 placeholder={header.title}
 bind:value={header.connected}
 on:change={() => setPage(1)}
/>
{/each}

The Header Title works as expected but the binding does not work. Is there any way that i can use it like this?

Upvotes: 0

Views: 1628

Answers (1)

Corrl
Corrl

Reputation: 7699

In the beginning the start value will be set to the value of test - since it's an empty string in your case, that can't be seen.

After the value of the input is changed the reactive log shows that the value of header.connected changes accordingly.
So the binding basically does work. Not sure if you expected test to change as well? How should everything then behave if there was more than one header object?

REPL

<script>
    let test = ""
    let headers = [
        {
            title: "header1",
            connected: test,
        },
        {
            title: "header2",
            connected: test,
        }
    ]

    function updateTest(event) {
        test = event.target.value
    }

    $: console.log('headers', headers)
</script>

<p>
    test: {test}
</p>

{#each headers as header}
<input
             type="text"
             placeholder={header.title}
             bind:value={header.connected}
             on:input={updateTest}
             />
{/each}

Upvotes: 1

Related Questions