Binding dynamic and dependent selects in Svelte

Viewed 823

I have a select component of which the options are dependent on the value of second select component. I would like the selected value of the first select to be the first of the dynamically provided options.

Here is a REPL that illustrates the issue. The options are updated, but the selected value is not updated in the parent App component. Additionally, when you first select the second or third option from the right dropdown, and then change the left one, it is not the first option that is selected in the right one.

This REPL has it working, but without the selects being child components.

There was a Svelte bug related to this, but this was solved in Svelte 3.23, see here

Any solution or workaround would be greatly appreciated.

2 Answers

To answer your second issue: You need to have a key for each option element within the select element. Only then Svelte can diff the list when the data changes.

ChildSelect.svelte would thus change to

<select bind:value={selectedChild}>
  {#each selectedParent.children as option (option.id)}
    <option value={option}>
      {option.text}
    </option>
  {/each}
</select>

The way your code is built, it seems that you want the value of selectedChild in App.svelte to be updated when ParentSelect is changed. To achieve that, you have to bind to it when using ParentSelect:

// App.svelte
<!--Old code-->
<!--<ParentSelect bind:selectedParent {selectedChild}></ParentSelect>-->

<!--New code-->
<ParentSelect bind:selectedParent bind:selectedChild></ParentSelect>

This way you'll end up binding selectedChild twice (in ParentSelect as well as in ChildSelect) but I've tried it in your repl and it seemed to work.

Related