Make custom Selects reactive

This commit is contained in:
2021-10-04 13:05:39 +02:00
parent 0d622ef69f
commit 4df9cdedd6
2 changed files with 94 additions and 14 deletions

View File

@@ -0,0 +1,46 @@
<script lang="ts">
import { createEventDispatcher } from 'svelte';
interface Option {
value: string
name: string
}
export let id: string
export let name: string
export let base: Option
export let options: Option[]
const dispatch = createEventDispatcher()
let current: number = 0
let currentOptionEl: HTMLElement
$: currentOption = options[current]
/**
* When changing select value
*/
const handleChange = ({ target: { value }}: any) => {
current = options.findIndex(option => option.value === value)
// Dispatch event to parent
dispatch('change', options[current].value)
}
</script>
<div class="select">
<slot />
<span bind:this={currentOptionEl}>
{currentOption.name}
</span>
<select {name} {id} on:change={handleChange}>
{#each options as { value, name }}
<option {value}>
{name}
</option>
{/each}
</select>
</div>