Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- App.svelte
- ```svelte
- <script module lang="ts">
- type MyCustomType = { id: number; name: string; }
- </script>
- <script lang="ts">
- import MyDropdown from "./MyDropdown.svelte";
- let items = [
- { id: 1, name: "Car" },
- { id: 2, name: "Boat" },
- { id: 3, name: "Plane" },
- ]
- let selectedValue: MyCustomType = $state(items[0]);
- let options = [
- {label: "Option 1", value: items[0] },
- {label: "Option 2", value: items[1] },
- {label: "Option 3", value: items[2] },
- ]
- </script>
- <MyDropdown
- bind:value={selectedValue}
- computeHtmlValue={(value: MyCustomType) => String(value.id)}
- options={options}
- />
- <h1>Selected value: {JSON.stringify(selectedValue)}</h1>
- ```
- MyDropdown.svelte
- ```svelte
- <!-- MyDropdown.svelte -->
- <script module lang="ts">
- type Item<T> = {
- value: T;
- label: string;
- }
- type Props<T> = {
- options: Array<Item<T>>;
- value?: T;
- onchange?: (newValue: T) => void;
- computeHtmlValue?: (value: T) => string | undefined;
- }
- </script>
- <script generics="T">
- let {
- options = [],
- value = $bindable(),
- onchange = undefined,
- computeHtmlValue = (value: T) => String(value)
- }: Props<T> = $props();
- let selectedValue = $derived(computeHtmlValue(value));
- const handleChange = (newValue: string) => {
- const selectedOption = options.find((opt) => computeHtmlValue(opt.value) === newValue);
- value = selectedOption?.value;
- onchange?.(value);
- }
- </script>
- <select value={selectedValue} onchange={(e) => handleChange(e.target!.value)}>
- {#each options as option, i}
- <option value={computeHtmlValue(option.value)}>{option.label}</option>
- {/each}
- </select>
- ```
Advertisement
Add Comment
Please, Sign In to add comment