How Binding Works in Svelte
You can bind elements to variables in Svelte. This way, any change to a variable will be reflected for the element and vice versa.
<!-- You can bind elements to variables, to reflect the value of the element in the variable -->
<input type="email" bind:value={user.email} />
You also have the option to use a shorthand in case the name and value matches:
<!-- The two lines below are equivalent -->
<input type="text" bind:value={value} />
<input type="text" bind:value />
If you want to bind variables to checkboxes, you need to use the bind:checked
directive:
<!-- Use the bind:checked for checkboxes -->
<input type="checkbox" bind:checked={user.consent} />
If you want to do the same with HTML content, you need to use bind:innerHTML
:
<!-- use bind:innerHTML to bind HTML -->
<article contenteditable=βtrueβ
bind:innerHTML={article.content}>
</article>
You can also bind to editable contents with the bind:textContent
directive:
<!-- use bind:textContent to bind to contenteditable -->
<h1 contenteditable="true"
bind:textContent={article.title}>
</h1>
Resources:
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: