mirror of
https://github.com/carbon-design-system/carbon-components-svelte.git
synced 2025-09-15 10:21:05 +00:00
fix(select): use first SelectItem
value as default if selected
is undefined (#1353)
Fixes #570
This commit is contained in:
parent
35031e800c
commit
f8b1c8a23a
2 changed files with 23 additions and 2 deletions
|
@ -71,8 +71,26 @@
|
|||
|
||||
const dispatch = createEventDispatcher();
|
||||
const selectedValue = writable(selected);
|
||||
const defaultSelectId = writable(null);
|
||||
const defaultValue = writable(null);
|
||||
|
||||
setContext("Select", { selectedValue });
|
||||
setContext("Select", {
|
||||
selectedValue,
|
||||
setDefaultValue: (id, value) => {
|
||||
/**
|
||||
* Use the first `SelectItem` value as the
|
||||
* default value if `selected` is `undefined`.
|
||||
*/
|
||||
if ($defaultValue === null) {
|
||||
defaultSelectId.set(id);
|
||||
defaultValue.set(value);
|
||||
} else {
|
||||
if ($defaultSelectId === id) {
|
||||
selectedValue.set(value);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
afterUpdate(() => {
|
||||
selected = $selectedValue;
|
||||
|
@ -80,7 +98,7 @@
|
|||
});
|
||||
|
||||
$: errorId = `error-${id}`;
|
||||
$: selectedValue.set(selected);
|
||||
$: selectedValue.set(selected ?? $defaultValue);
|
||||
</script>
|
||||
|
||||
<div class:bx--form-item="{true}" {...$$restProps}>
|
||||
|
|
|
@ -13,8 +13,11 @@
|
|||
|
||||
import { getContext, onMount } from "svelte";
|
||||
|
||||
const id = "ccs-" + Math.random().toString(36);
|
||||
const ctx = getContext("Select") || getContext("TimePickerSelect");
|
||||
|
||||
$: ctx?.setDefaultValue?.(id, value);
|
||||
|
||||
let selected = false;
|
||||
|
||||
const unsubscribe = ctx.selectedValue.subscribe((currentValue) => {
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue