Use directive syntax in Svelte to add special behavior to HTML elements easily. It helps you control how elements work without writing extra JavaScript.
Use directive syntax in 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.
isVisible is true.{#if isVisible}
<p>Visible content</p>
{/if}handleClick function when the button is clicked.<button on:click={handleClick}>Click me</button>items array and creates a list item for each.{#each items as item}
<li>{item}</li>
{/each}name variable updated with the input field value.<input bind:value={name} placeholder="Enter your name">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.
<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>
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.
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.