November 10, 2020
How to focus on a dynamically added input field in Svelte?
In svelte, we can focus on newly added inputs in two different ways:
use:action
Actions are functions that are called when an element is created.
<script>
  let inputs = [];
  function addInput() {
    inputs = […inputs, { title: "" }];
  }
  function callFocus(input){
    input.focus();
  }
</script>
{#each inputs as i}
  <input type="text" bind:value={i.title} use:callFocus />
{/each}
<button on:click={addInput}>Add Input Field</button>autofocus Attribute:
<script>
  let inputs = [];
  function addInput() {
    inputs = […inputs, { title: "" }];
  }
</script>
{#each inputs as i}
  <input type="text" bind:value={i.title} autofocus />
{/each}
<button on:click={addInput}>Add Input Field</button>