Svelte Bindings

Using Svelte you can create a two-way binding between data and the UI.

Many other Web frameworks can provide two-way bindings, it’s a very common pattern.

They are especially useful with forms.

bind:value

Let’s start with the most common form of binding you’ll often use, which you can apply using bind:value. You take a variable from the component state, and you bind it to a form field:

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

<input bind:value={name}>

Now if name changes, the input field will update its value. And the opposite is true, as well: if the form is updated by the user, the name variable value changes.

Just be aware that the variable must be defined using let/var and not const, otherwise it can’t be updated by Svelte, as const defines a variable with a value that can’t be reassigned.

bind:value works on all flavors of input fields (type="number"type="email" and so on), but it also works for other kind of fields, like textarea and select (more on select later).

Leave a comment

Your email address will not be published. Required fields are marked *