How Binding Works in Svelte

How Binding Works in Svelte

Ferenc Almasi β€’ 2020 September 25 β€’ Read time 1 min read
  • twitter
  • facebook

You can bind elements to variables in Svelte. This way, any change to a variable will be reflected for the element and vice versa.

Copied to clipboard!
<!-- You can bind elements to variables, to reflect the value of the element in the variable -->
<input type="email" bind:value={user.email} />
Binding.svelte

You also have the option to use a shorthand in case the name and value matches:

Copied to clipboard!
<!-- The two lines below are equivalent -->
<input type="text" bind:value={value} />
<input type="text" bind:value />
Binding.svelte

If you want to bind variables to checkboxes, you need to use the bind:checked directive:

Copied to clipboard!
<!-- Use the bind:checked for checkboxes -->
<input type="checkbox" bind:checked={user.consent} />
Binding.svelte

If you want to do the same with HTML content, you need to use bind:innerHTML:

Copied to clipboard!
<!-- use bind:innerHTML to bind HTML -->
<article contenteditable=”true”
         bind:innerHTML={article.content}>
</article>
Binding.svelte

You can also bind to editable contents with the bind:textContent directive:

Copied to clipboard!
<!-- use bind:textContent to bind to contenteditable -->
<h1 contenteditable="true"
    bind:textContent={article.title}>
</h1>
Binding.svelte
How Binding Works in Svelte
If you would like to see more Webtips, follow @flowforfrank

Looking into Svelte 3

Resources:

  • twitter
  • facebook
Did you find this page helpful?
πŸ“š More Webtips
Mentoring

Rocket Launch Your Career

Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies:

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.