I have a Svelte Selection that fetches data and displays it in a dropdown. Users can select various properties, and this functionality works well. However, now I want to preselect certain options; despite trying various approaches, I have been unable to make it work for some reason.
{#if properties.length > 0 && selectedProperties.length > 0}<div class="pb-16"><label for="propertyDropdown">Select Company Properties:</label><select id="propertyDropdown" bind:value={selectedProperties} on:change={handlePropertySelection} class="styled-dropdown" multiple> {#each properties as {name, label}}<option title={name} value={name}>{label}</option> {/each}</select></div>{/if}
I call this method onMount
to prefill the selection by setting selectedProperties
:
let selectedProperties: string[];...const handleCodeReceived = async function (code: string) { try { accessToken = await handleAuthentication(code) ?? ""; if (accessToken) { properties = await fetchCompanyProperties(accessToken); const selectedOptions = Array.from(properties.filter((property) => !property.hidden).map((option) => option.name)); selectedProperties = selectedOptions; } } catch (error: any) { errorMessage = error.message; }};
Note that the manual selection works just fine and the moment I manually want to select one element the preselected elements are suddenly now also selected. This also proves that the selectedProperties
array is getting filled with the right data, there just seems to be some sort of problem with the Svelte UI State. Help is greatly appreciated.
const handlePropertySelection = (event: Event) => { const selectElement = event.target as HTMLSelectElement; const selectedOptions = Array.from(selectElement.selectedOptions).map((option) => option.value); selectedProperties = selectedOptions;};
I