Slim binding

How to use bindings in Svelte

With Svelte, you can create a two-way binding between data and UI.

Many other web frameworks can provide two-way binding, which is a very common pattern.

They are particularly useful for tables.

Binding: value

Let’s start with the most commonly used form of binding, you can usebind:value. You get the variable from the component state and bind it to the form field:

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

<input bind:value={name}>

Now ifnameChanging the input field will update its value. The reverse is also true: if the form is updated by the user, thennameThe variable value changes.

Please note that you must uselet/varIs notconst, Otherwise Svelte cannot update it becauseconstDefine a variable whose value cannot be reassigned.

bind:valueApplicable to all types of input fields (type="number",type="email"Etc.), but it also applies to other types of fields, such astextareawithselect(More onselectafter that).

Checkboxes and radio buttons

Checkboxes and broadcast input (inputWith elementstype="checkbox"ortype="radio") The following 3 bindings are allowed:

  • bind:checked
  • bind:group
  • bind:indeterminate

bind:checkedAllows us to bind the value to the checked state of the element:

<script>
let isChecked
</script>

<input type=checkbox bind:checked={isChecked}>

bind:groupCheckboxes and radio inputs are very convenient because they are often used in groups. usebind:groupYou can associate a JavaScript array with a checkbox list and fill it according to the user's choice.

This is an example. ThisgoodDogsThe array is filled according to the checkboxes I ticked:

<script>
let goodDogs = []
let dogs = ['Roger', 'Syd']
</script>

<h2> Who’s a good dog? </h2>

<ul> {#each dogs as dog} <li>{dog} <input type=checkbox bind:group={goodDogs} value={dog}></li> {/each} </ul>

<h2> Good dogs according to me: </h2>

<ul> {#each goodDogs as dog} <li>{dog}</li> {/each} </ul>

See the example belowhttps://svelte.dev/repl/059c1b5edffc4b058ad36301dd7a1a58

bind:indeterminateAllow us to bind toindeterminateThe status of the element (if you want to learn more, please visithttps://css-tricks.com/indeterminate-checkboxes/)

Select field

bind:valueAlso applies toselectForm field to get the value that automatically assigns the selected value to the variable:

<script>
let selected
</script>

<select bind:value={selected}> <option value=“1”>1</option> <option value=“2”>2</option> <option value=“3”>3</option> </select>

{selected}

The great thing is that if you dynamically generate options from an array of objects, the selected option is now an object, not a string:

<script>
let selected

const goodDogs = [ { name: ‘Roger’ }, { name: ‘Syd’ } ] </script>

<h2>List of possible good dogs:</h2> <select bind:value={selected}> {#each goodDogs as goodDog} <option value={goodDog}>{goodDog.name}</option> {/each} </select>

{#if selected} <h2> Good dog selected: {selected.name} </h2> {/if}

See example:https://svelte.dev/repl/7e06f9b7becd4c57880db5ed184ea0f3

selectAlso allowedmultipleAttributes:

<script>
let selected = []

const goodDogs = [ { name: ‘Roger’ }, { name: ‘Syd’ } ] </script>

<h2>List of possible good dogs:</h2> <select multiple bind:value={selected}> {#each goodDogs as goodDog} <option value={goodDog}>{goodDog.name}</option> {/each} </select>

{#if selected.length} <h2>Good dog selected:</h2> <ul> {#each selected as dog} <li>{dog.name}</li> {/each} </ul> {/if}

See example:https://svelte.dev/repl/b003248e87f04919a2f9fed63dbdab8c

Other binding

Depending on the HTML markup you are dealing with, you can apply different kinds of bindings.

bind:filesIs a valid bindingtype="file"Enter the element to bind the list of selected files.

ThisdetailsHTML elements allowedbind:openBind its on/off value.

ThisaudiowithvideoMedia HTML tags allow you to bind several of their attributes:currentTime,duration,paused,buffered,seekable,played,volume,playbackRate.

textContentwithinnerHTMLCan be boundcontenteditablefield.

For those specific HTML elements, all content is very useful.

Read-only binding

offsetWidth,offsetHeight,clientWidth,clientHeightCan be boundRead onlyDo not include empty tags on any block-level HTML elements (e.g.br) And elements set as inline (display: inline).

Get references to HTML elements in JavaScript

bind:thisIs a special binding that allows you to obtain a reference to an HTML element and bind it to a JavaScript variable:

<script>
let myInputField
</script>

<input bind:this={myInputField} />

When you need to apply logic to the element after installing it (for example, useonMount()Life cycle event callback.

Binding props

usebind:You can bind the value to any prop exposed by the component.

Say you have oneCar.svelteingredient:

<script>
export let inMovement = false
</script>

<button on:click={() => inMovement = true }>Start car</button>

You can import components and bindinMovementpillar:

<script>
  import Car from './Car.svelte';

let carInMovement; </script>

<Car bind:inMovement={carInMovement} />

{carInMovement}

This can consider some interesting situations.

Download mine for freeSlim Handbook


More subtle tutorials: