0
0
Svelteframework~5 mins

Use directive syntax in Svelte

Choose your learning style9 modes available
Introduction

Use directive syntax in Svelte to add special behavior to HTML elements easily. It helps you control how elements work without writing extra JavaScript.

When you want to show or hide content based on a condition.
When you need to run code when an event happens, like a button click.
When you want to loop over a list and create repeated elements.
When you want to bind a variable to an input field to keep data in sync.
Syntax
Svelte
{#directive} ... {/directive}

or

<element on:event={handler}>

or

<input bind:value={variable}>

Directives start with special keywords like {#if}, {#each}, or attributes like on: and bind:.

They make your code cleaner by handling common tasks declaratively.

Examples
Shows the paragraph only if isVisible is true.
Svelte
{#if isVisible}
  <p>Visible content</p>
{/if}
Runs handleClick function when the button is clicked.
Svelte
<button on:click={handleClick}>Click me</button>
Loops over items array and creates a list item for each.
Svelte
{#each items as item}
  <li>{item}</li>
{/each}
Keeps the name variable updated with the input field value.
Svelte
<input bind:value={name} placeholder="Enter your name">
Sample Program

This Svelte component shows a button that counts clicks, a greeting that updates as you type your name, and a list of fruits. It uses on:click to handle clicks, {#if} to conditionally show the greeting, bind:value to sync input with a variable, and {#each} to loop over items.

Svelte
<script>
  let isVisible = true;
  let count = 0;
  let name = '';
  let items = ['Apple', 'Banana', 'Cherry'];

  function handleClick() {
    count += 1;
  }
</script>

<button on:click={handleClick}>Clicked {count} times</button>

{#if isVisible}
  <p>Hello {name || 'guest'}!</p>
{/if}

<input bind:value={name} placeholder="Type your name">

<ul>
  {#each items as item}
    <li>{item}</li>
  {/each}
</ul>
OutputSuccess
Important Notes

Use {#if} and {#each} blocks to control what appears on the page.

Use on:event to listen for user actions like clicks or typing.

Use bind: to keep variables and inputs in sync automatically.

Summary

Use directive syntax to add interactive behavior easily in Svelte.

Directives include {#if}, {#each}, on:, and bind:.

They help keep your code simple and readable.