0
0
SvelteHow-ToBeginner · 3 min read

How to Use Two Way Binding in Svelte: Simple Guide

In Svelte, two way binding is done using the bind: directive on form elements like input. This keeps the variable and the input value in sync automatically, so when one changes, the other updates too.
📐

Syntax

Use bind:value={variable} on form elements to link the element's value to a variable. This means when the user types, the variable updates, and if the variable changes in code, the input updates too.

Example parts:

  • bind:value: directive to connect value
  • {variable}: the JavaScript variable to sync
svelte
<input bind:value={name} />
Output
An input box that updates the variable 'name' as you type and updates if 'name' changes in code.
💻

Example

This example shows a text input bound to a variable name. The heading updates live as you type, showing two way binding in action.

svelte
<script>
  let name = '';
</script>

<input bind:value={name} placeholder="Type your name" />
<h2>Hello, {name}!</h2>
Output
An input box with placeholder 'Type your name' and a heading below that says 'Hello, ' followed by whatever you type in real time.
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to use bind:value and using value alone, which makes the input read-only.
  • Trying to bind to non-form elements that don't support value.
  • Not declaring the variable with let in the script, causing errors.
svelte
<!-- Wrong: no bind, input won't update variable -->
<input value={name} />

<!-- Right: use bind:value for two way binding -->
<input bind:value={name} />
📊

Quick Reference

Tips for two way binding in Svelte:

  • Use bind:value on inputs, selects, and textareas.
  • Variables must be declared with let to be reactive.
  • Two way binding keeps UI and data in sync automatically.
  • Works only on elements that have a value property.

Key Takeaways

Use bind:value to connect input values with variables for automatic syncing.
Declare variables with let to make them reactive and bindable.
Two way binding updates both the UI and the variable instantly as changes happen.
Avoid using value without bind: for inputs if you want two way binding.
Two way binding works only on form elements that support a value property.