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 variable input 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 the input 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 the input variable.

  • <button>Change name</button>: This button currently has no functionality attached to it.

Additional Information

Two-way binding is very useful for form elements where you want to keep the UI and the state in sync.

Warning

Last updated