1

I'm having a little trouble with updating variables using nested files. My expectation is that when the checkmark is checked, the variable switchTouch is updated. I'm clearly doing something incorrectly as this isn't the case. Any pointers would be welcomed:

<script>
    import Control from './Control.svelte'
    
    let switchTouch = false
    let switchScreen = true
    
     let controls = [
    { id: 1, title: 'Touch Targets', checked: switchTouch },
    { id: 2, title: 'Screen Reader', checked: switchScreen }
  ];
    
$: console.log(switchTouch)

</script>

{#each controls as control}
<Control title={control.title} bind:value={control.checked} />          
{/each}

The REPL I'm using for a more detailed example

2 Answers 2

4

The first issue with your code is that you are binding value instead of checked

<Control title={control.title} bind:value={control.checked} />

should be

<Control title={control.title} bind:checked={control.checked} />

The second is that your code sets the initial value of the control to switchTouch but this is just an assignment, nowhere in your code are you making a link back from the control to switchTouch. This can be easily solved using a reactive statement however:

$: switchTouch = controls[0].checked

This will update switchTouch everytime the checked property of the first control changes effectively creating a link between the two variables.

1

The controls are updated in your code, I believe that you want to see the component changes in your App.svelte you can do that by exporting a variable and use afterUpdate lifecycle to send the changes. I wrote a small snippet that will be useful check REPL

Not the answer you're looking for? Browse other questions tagged or ask your own question.