Bird
Raised Fist0
Svelteframework~10 mins

Use directive syntax in Svelte - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Use directive syntax
Start Svelte Component
↓
Parse Template
↓
Identify Directive Syntax
↓
Bind Directive to Behavior
↓
Render DOM with Directive Effects
↓
User Interaction or State Change
↓
Directive Reacts and Updates DOM
↓
Component Reflects Changes
↓
End
Svelte reads the template, finds directives, binds them to behaviors, renders DOM, and updates reactively on changes.
Execution Sample
Svelte
<script>
  let count = 0;
</script>
<button on:click={() => count++}>Clicked {count} times</button>
A button uses the 'on:click' directive to increase count and update the displayed text.
Execution Table
StepActionDirective DetectedState BeforeState AfterDOM Update
1Parse <button>on:clickcount = 0count = 0Button rendered with text 'Clicked 0 times'
2User clicks buttonon:click triggeredcount = 0count = 1Button text updates to 'Clicked 1 time'
3User clicks button againon:click triggeredcount = 1count = 2Button text updates to 'Clicked 2 times'
4No further clicksNo directive triggeredcount = 2count = 2DOM remains 'Clicked 2 times'
💡 User stops clicking; no more directive events triggered.
Variable Tracker
VariableStartAfter 1After 2Final
count0122
Key Moments - 2 Insights
Why does the button text update automatically when count changes?
Because the 'on:click' directive triggers a state change, and Svelte's reactive system updates the DOM as shown in execution_table rows 2 and 3.
What does the 'on:click' directive do in the code?
It listens for the click event on the button and runs the provided function to increment 'count', as seen in execution_table steps 2 and 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'count' after the second click?
A1
B2
C0
D3
💡 Hint
Check the 'State After' column at Step 3 in the execution_table.
At which step does the DOM text update to 'Clicked 1 time'?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look at the 'DOM Update' column in execution_table for when the text changes to 'Clicked 1 time'.
If the user never clicks the button, what will the displayed text be?
A'Clicked 2 times'
B'Clicked 1 times'
C'Clicked 0 times'
DNo text displayed
💡 Hint
Refer to execution_table Step 1 where initial rendering happens without clicks.
Concept Snapshot
Svelte directives use syntax like on:event={handler}.
They bind DOM events or behaviors directly in markup.
When events happen, state changes trigger reactive updates.
Example: on:click increments a variable and updates UI.
Directives keep code simple and reactive without extra setup.
Full Transcript
This example shows how Svelte uses directive syntax to bind events. The 'on:click' directive listens for clicks on a button. When clicked, it runs a function that increases the 'count' variable. Svelte automatically updates the button text to show the new count. The execution table traces parsing, user clicks, state changes, and DOM updates step-by-step. The variable tracker shows how 'count' changes from 0 to 2 after two clicks. Key moments clarify why the UI updates and what the directive does. The quiz tests understanding of state and DOM changes from the table. Overall, directives in Svelte connect user actions to reactive UI updates simply and clearly.

Practice

(1/5)
1. Which Svelte directive is used to conditionally show content based on a boolean value?
{#if}, {#each}, on:, or bind:?
easy
A. bind:
B. {#if}
C. on:
D. {#each}

Solution

  1. Step 1: Understand the purpose of {#if}

    The {#if} directive in Svelte shows or hides content based on a condition.
  2. Step 2: Compare with other directives

    {#each} loops over lists, on: handles events, and bind: links variables to inputs.
  3. Final Answer:

    {#if} -> Option B
  4. Quick Check:

    Conditional display = {#if} [OK]
Hint: Use {#if} to show/hide content based on true/false [OK]
Common Mistakes:
  • Confusing {#if} with {#each} for loops
  • Using on:click for conditional display
  • Trying to bind variables for conditionals
2. Which of the following is the correct syntax to listen for a click event on a button in Svelte?
easy
A. <button onClick={handleClick}>Click</button>
B. <button click={handleClick}>Click</button>
C. <button on:click={handleClick}>Click</button>
D. <button bind:click={handleClick}>Click</button>

Solution

  1. Step 1: Recall Svelte event directive syntax

    Svelte uses on:eventName={handler} to listen to events like clicks.
  2. Step 2: Check each option

    <button on:click={handleClick}>Click</button> uses on:click correctly. Options A, B, and D use incorrect or invalid syntax.
  3. Final Answer:

    <button on:click={handleClick}>Click</button> -> Option C
  4. Quick Check:

    Event listener syntax = on:event [OK]
Hint: Use on:eventName={handler} to listen for events [OK]
Common Mistakes:
  • Using camelCase like onClick instead of on:click
  • Trying to bind events with bind:
  • Omitting the on: prefix
3. What will be the rendered output of this Svelte code?
<script>
  let items = ['apple', 'banana'];
</script>

<ul>
  {#each items as item}
    <li>{item}</li>
  {/each}
</ul>
medium
A.
  • apple
  • banana
B.
  • items
C.
  • {item}
  • {item}
D. Syntax error

Solution

  1. Step 1: Understand the {#each} directive

    The {#each} directive loops over the array items and assigns each element to item.
  2. Step 2: Render list items

    For each item, it creates a <li> element with the item text inside.
  3. Final Answer:

    <ul><li>apple</li><li>banana</li></ul> -> Option A
  4. Quick Check:

    Loop items render as list =
    • apple
    • banana
    [OK]
Hint: Each loops output list items for each array element [OK]
Common Mistakes:
  • Expecting the literal string {item} to show
  • Confusing the array name with item variable
  • Thinking it causes a syntax error
4. Identify the error in this Svelte snippet:
<script>
  let count = 0;
</script>

<button on:click="count++">Increment</button>
<p>Count: {count}</p>
medium
A. Using double quotes around the event handler expression
B. Missing bind: directive on count variable
C. Incorrect variable name count
D. No error, code works fine

Solution

  1. Step 1: Check event handler syntax

    Svelte requires event handlers to use curly braces without quotes: on:click={count++}.
  2. Step 2: Identify the error

    The code uses quotes around the expression, which causes a syntax error.
  3. Final Answer:

    Using double quotes around the event handler expression -> Option A
  4. Quick Check:

    Event handler must be unquoted expression [OK]
Hint: Use curly braces, not quotes, for event handlers [OK]
Common Mistakes:
  • Putting event handler code inside quotes
  • Trying to bind variables unnecessarily
  • Assuming variable name is wrong
5. You want to create a Svelte component that shows a list of tasks and lets the user toggle each task's completion status by clicking a checkbox. Which directive syntax combination correctly binds the checkbox state and updates the task's done property?
hard
A.
<ul>
  {#each tasks as task}
    <li>
      <input type="checkbox" on:click={task.done = !task.done} /> {task.text}
    </li>
  {/each}
</ul>
B.
<ul>
  {#each tasks as task}
    <li>
      <input type="checkbox" checked={task.done} on:change={() => task.done = !task.done} /> {task.text}
    </li>
  {/each}
</ul>
C.
<ul>
  {#each tasks as task}
    <li>
      <input type="checkbox" bind:value={task.done} /> {task.text}
    </li>
  {/each}
</ul>
D.
<script>
  let tasks = [
    { id: 1, text: 'Task 1', done: false },
    { id: 2, text: 'Task 2', done: true }
  ];
</script>

<ul>
  {#each tasks as task}
    <li>
      <input type="checkbox" bind:checked={task.done} /> {task.text}
    </li>
  {/each}
</ul>

Solution

  1. Step 1: Understand binding checkbox state

    In Svelte, bind:checked links the checkbox's checked state directly to a variable, updating it automatically.
  2. Step 2: Analyze each option

    <script>
      let tasks = [
        { id: 1, text: 'Task 1', done: false },
        { id: 2, text: 'Task 2', done: true }
      ];
    </script>
    
    <ul>
      {#each tasks as task}
        <li>
          <input type="checkbox" bind:checked={task.done} /> {task.text}
        </li>
      {/each}
    </ul>
    uses bind:checked={task.done}, which is correct.
    <ul>
      {#each tasks as task}
        <li>
          <input type="checkbox" checked={task.done} on:change={() => task.done = !task.done} /> {task.text}
        </li>
      {/each}
    </ul>
    manually toggles on change but is more complex.
    <ul>
      {#each tasks as task}
        <li>
          <input type="checkbox" bind:value={task.done} /> {task.text}
        </li>
      {/each}
    </ul>
    uses bind:value which is incorrect for checkboxes.
    <ul>
      {#each tasks as task}
        <li>
          <input type="checkbox" on:click={task.done = !task.done} /> {task.text}
        </li>
      {/each}
    </ul>
    uses on:click without binding, which is less reactive.
  3. Final Answer:

    bind:checked={task.done} -> Option D
  4. Quick Check:

    Checkbox bind:checked updates variable automatically [OK]
Hint: Use bind:checked to sync checkbox with boolean variable [OK]
Common Mistakes:
  • Using bind:value instead of bind:checked for checkboxes
  • Manually toggling state instead of binding
  • Using on:click without reactive binding
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard