by Sai gowtham

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>

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
26,545 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
221,520 students enrolled
44 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
114,575 students enrolled
21 hours of video content
View Course