Two-way-binding Shortcut
Two-way binding in Svelte allows you to synchronize the value of an input field with a variable in your script. This means any changes in the input field will update the variable, and any changes to the variable will update the input field.
Original Code Example
Let's start with the original code provided:
<script>
let input = 'Shento';
</script>
<h1>Hello my name is {input}</h1>
<input type="text" bind:value={input} /><button>Change name</button>
Explanation
Script Section
<script>
let input = 'Shento';
</script>
let input = 'Shento';
: This line initializes a variableinput
with the value 'Shento'. In Svelte, you can use any variable name you like here.
HTML Section
<h1>Hello my name is {input}</h1>
<input type="text" bind:value={input} /><button>Change name</button>
<h1>Hello my name is {input}</h1>
: This line displays the value of theinput
variable inside the<h1>
tag.<input type="text" bind:value={input} />
: This is a Svelte-specific syntax for two-way binding. It binds the value of the input field to theinput
variable.<button>Change name</button>
: This button currently has no functionality attached to it.
Additional Information
Warning
Ensure that the variable used in the bind:value
directive is initialized in the script section to avoid runtime errors.
Last updated