fix(checkbox): fix two-way binding (#1042)

Fixes #967
This commit is contained in:
metonym 2022-01-26 19:04:32 -08:00 committed by GitHub
commit 048ebc7b81
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 13 additions and 9 deletions

View file

@ -462,7 +462,7 @@ None.
| Prop name | Kind | Reactive | Type | Default value | Description |
| :------------ | :--------------- | :------- | :---------------------------------------- | ------------------------------------------------ | ------------------------------------------------- |
| ref | <code>let</code> | Yes | <code>null &#124; HTMLInputElement</code> | <code>null</code> | Obtain a reference to the input HTML element |
| group | <code>let</code> | Yes | <code>any[]</code> | <code>[]</code> | Specify the bound group |
| group | <code>let</code> | Yes | <code>any[]</code> | <code>undefined</code> | Specify the bound group |
| checked | <code>let</code> | Yes | <code>boolean</code> | <code>false</code> | Specify whether the checkbox is checked |
| value | <code>let</code> | No | <code>any</code> | <code>""</code> | Specify the value of the checkbox |
| indeterminate | <code>let</code> | No | <code>boolean</code> | <code>false</code> | Specify whether the checkbox is indeterminate |

View file

@ -735,7 +735,6 @@
"kind": "let",
"description": "Specify the bound group",
"type": "any[]",
"value": "[]",
"isFunction": false,
"isFunctionDeclaration": false,
"constant": false,

View file

@ -16,7 +16,7 @@
* Specify the bound group
* @type {any[]}
*/
export let group = [];
export let group = undefined;
/** Specify whether the checkbox is indeterminate */
export let indeterminate = false;
@ -59,6 +59,8 @@
const dispatch = createEventDispatcher();
$: useGroup = Array.isArray(group);
$: checked = useGroup ? group.includes(value) : checked;
$: dispatch("check", checked);
</script>
@ -85,7 +87,7 @@
bind:this="{ref}"
type="checkbox"
value="{value}"
checked="{checked || group.includes(value)}"
checked="{checked}"
disabled="{disabled}"
id="{id}"
indeterminate="{indeterminate}"
@ -94,10 +96,13 @@
readonly="{readonly}"
class:bx--checkbox="{true}"
on:change="{() => {
checked = !checked;
group = group.includes(value)
? group.filter((_value) => _value !== value)
: [...group, value];
if (useGroup) {
group = group.includes(value)
? group.filter((_value) => _value !== value)
: [...group, value];
} else {
checked = !checked;
}
}}"
on:change
on:blur

View file

@ -16,7 +16,7 @@ export interface CheckboxProps {
/**
* Specify the bound group
* @default []
* @default undefined
*/
group?: any[];