Chris Talman
Chris Talman

Reputation: 1169

Does Svelte support checkbox binding?

Does Svelte support bindings for checkboxes?

I am aware that the documentation says the following, so it is possible that it has yet to be implemented.

Two-way binding is not yet fully implemented. Check back soon for the full list of available bindings!

I imagine that the implementation would look something like this.

<input type="checkbox" bind:checked="checked">

However, when I try this at the moment, it does not seem to work.

Update

Upon further investigation, it seems that the binding is working in some way, with the bound value changing in the component data. However, for some reason, changes are not being reflected in the DOM. They can be reflected by simply setting the data to be itself (component.set({checked: component.get('checked')})), forcing a DOM update, but they are not being reflected automatically, as they should with binding.

Update 2

I have created a REPL to demonstrate this problem.

Upvotes: 4

Views: 4335

Answers (2)

sudo bangbang
sudo bangbang

Reputation: 28229

This can be done with

<script>
     let checked = false;
</script>


<input type=checkbox bind:checked={checked}>

Now the variable checked is bound to the value of checkbox.

You can try this in this neat little example

Upvotes: 1

Rich Harris
Rich Harris

Reputation: 29615

In your example, you need to bind the component as well as the <input> element:

<Component bind:checked="checked"></Component>

You can see it working here.

Upvotes: 2

Related Questions