phiwhynot
phiwhynot

Reputation: 39

bind:checked 2 ways binding update programmatically

I have an array of objects with 2 properties (name and selected) and I would like to be able to select / deselect checkboxes when I click on a button. The bind:checked is binded to the "selected" property of my object. The thing is when I click the button, the toggle function is called, "selected" is updated for each objects but the status of the checkboxes are not updated.

Here is an example to illustrate my problem:

<script>
    let agrumes = [
        {name: "Citron", selected: false},
        {name: "Orange", selected: false},
        {name: "Pamplemousse", selected: false}
    ]
    
    function toggle() {
        agrumes.forEach(element => {
            element.selected = !element.selected;
        });     
        console.log(agrumes);
    }   
</script>

<button on:click="{() => toggle()}">Click me</button>
<br />

{#each agrumes as agrume}
<input type="checkbox" id="{agrume.name}" bind:checked={agrume.selected}/>
<label for="{agrume.name}">{agrume.name}</label>
{/each}

Do you know how can I solve it?

Thanks

Upvotes: 1

Views: 858

Answers (1)

Corrl
Corrl

Reputation: 7721

The problem is similar to e.g. using .push() which is described in the docs under Assignments are 'reactive'
To trigger the update you can either add an assignment of the modified array to itself after the iteration

  agrumes.forEach(element => {
    element.selected = !element.selected;
  });     
  agrumes = agrumes

or use .map() instead REPL

agrumes = agrumes.map(element => {
  element.selected = !element.selected;
  return element
});

Upvotes: 1

Related Questions