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 ifname
Changing the input field will update its value. The reverse is also true: if the form is updated by the user, thenname
The variable value changes.
Please note that you must use
let/var
Is notconst
, Otherwise Svelte cannot update it becauseconst
Define a variable whose value cannot be reassigned.
bind:value
Applicable to all types of input fields (type="number"
,type="email"
Etc.), but it also applies to other types of fields, such astextarea
withselect
(More onselect
after that).
Checkboxes and radio buttons
Checkboxes and broadcast input (input
With elementstype="checkbox"
ortype="radio"
) The following 3 bindings are allowed:
bind:checked
bind:group
bind:indeterminate
bind:checked
Allows us to bind the value to the checked state of the element:
<script>
let isChecked
</script>
<input type=checkbox bind:checked={isChecked}>
bind:group
Checkboxes and radio inputs are very convenient because they are often used in groups. usebind:group
You can associate a JavaScript array with a checkbox list and fill it according to the user's choice.
This is an example. ThisgoodDogs
The 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:indeterminate
Allow us to bind toindeterminate
The status of the element (if you want to learn more, please visithttps://css-tricks.com/indeterminate-checkboxes/)
Select field
bind:value
Also applies toselect
Form 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
select
Also allowedmultiple
Attributes:
<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:files
Is a valid bindingtype="file"
Enter the element to bind the list of selected files.
Thisdetails
HTML elements allowedbind:open
Bind its on/off value.
Thisaudio
withvideo
Media HTML tags allow you to bind several of their attributes:currentTime
,duration
,paused
,buffered
,seekable
,played
,volume
,playbackRate
.
textContent
withinnerHTML
Can be boundcontenteditable
field.
For those specific HTML elements, all content is very useful.
Read-only binding
offsetWidth
,offsetHeight
,clientWidth
,clientHeight
Can 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:this
Is 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.svelte
ingredient:
<script>
export let inMovement = false
</script>
<button on:click={() => inMovement = true }>Start car</button>
You can import components and bindinMovement
pillar:
<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:
- Getting started with Svelte-short tutorial
- How to use props in Svelte
- How to import components in Svelte
- How to export functions and variables from Svelte components
- Slim template: conditional logic
- How to re-render Svelte components on demand
- Slim slot
- How to add comments in Svelte templates
- Slim binding
- Handling status updates in Svelte
- Reactive statements in Svelte
- Slim life cycle events
- Slim template: loop
- Resolve the promise in the Svelte template
- Dealing with Svelte's activities
- Svelte's cross-component state management
- How to access URL parameters in Sapper outside the script module
- How to dynamically apply CSS in Svelte
- How to redirect to URL in Sapper
- How to simulate for loop in Svelte template