Attribute binding in Svelte.js

Attribute binding in Svelte.js

In this tutorial, we are going to learn about how to bind HTML attributes in svelte.

This is our starting code.

App.svelte
<script>
  let src = "rose.jpg";
</script>


<h1>This is my first svelte app</h1>
<img />

To bind the attributes in svelte we need to use curly brace syntax { } so that it can evaluate the JavaScript expression.

App.svelte
<script>
  let src = "rose.jpg";
</script>

<h1>This is my first svelte app</h1>
 // attribute binding<img src={src} />

atrribute-binding-example

Shorthand attributes

If the attribute name and value is matched like in above code src={src} it can be replaced by {src}.

<img {src} />

Similarly, we can bind other HTML attributes by using { } curly brace syntax.

<script>
   let disabled = true;
   let google = "https://www.google.com"
</script>

//disabled button
<button {disabled}>Click</button>
<a href={google}>Google</a>