Asked By: Anonymous
I am new to Svelte and there are things I suppose should be easy to do and yet they give me trouble. In a small Svelte app I have this HTML:
<div class="mt-5 mb-6">
<Switch on:click={toggle} /> <span>{stat}</span>
</div>
I need to display "On" or "Off" in the span element, depending on the "state" of the switch. For this purpose, I have:
import Switch from './Switch.svelte';
let stat = 'off';
let status = false;
function toggle () {
status = !status;
stat = status ? "on" : "off";
}
See REPL here.
For a reason I can not understand, even though there’s no error in the console, the span always shows "Off". Why?
Solution
Answered By: Anonymous
You are making it too complicated. You can easily bind to the checked value of the underlying component:
<script>
import Switch from './Switch.svelte';
let status;
</script>
<div>
<Switch bind:checked={status} /> <span>{status ? "on" : "off"}</span>
</div>
Before, you tried to listen to an click event, which your Switch
component does not have, that is why it did not work. But as it is a checkbox, it has the checked property. Find more info here.