javascripthtmlcheckboxsveltesvelte-component

Svelte Checkbox input state does not match to html checkbox state


I am having problems with my custom checkbox component.

My goal is for the parant to have control over the selected state of the input. But every time I click the checkbox it gets selected even if nothing is set in the parent. I suspect it is not directly related to Svelte more like to the checkbox behavior.

<script lang="ts">
  import { createEventDispatcher } from "svelte";

  export let checked = false;

  const dispatch = createEventDispatcher();

  function handleClick(event) {
    // Emit a custom event to notify the parent that the checkbox was clicked
    dispatch('click', { checked: !checked });
  }
</script>

<input type="checkbox" checked={checked} on:click={handleClick} />

<style>
  input[type='checkbox']:not(:disabled):is(:checked) {
   height: 35px;
   width: 35px;
  }
</style>

What am I missing here?

I tryied custom events, two way binding but nothings helps. Here is a stackblitz link if want to test.

Thank you


Solution

  • You need bind:checked={checked} check to synchronize the state to the property and if at the usage site the state should also be synchronized, you need to use bind:checked={...} there as well. Otherwise it's one-directional into the element/component.

    (The state in the click event handler will lag behind, generally I would not use click but change instead.)