6

How can one render an attribute on a html element conditionally with svelte? To be clear, I am not talking about a conditional value, but the attribute presence itself.

For instance, I want to autofocus only the first item in this list of inputs:

{{#each codeInputs as codeInput, index}}
  <input bind:value="inputCodes[index]" type="text" autofocus> 
{{/each}}

The attribute autofocus should be there only for the first item. I could use index to detect the first item, but autofocus="{{index===0}}" renders autofocus="true" or "false", so that is not what I need.

Also see https://github.com/sveltejs/svelte/issues/259

dschulten
  • 2,994
  • 1
  • 27
  • 44

1 Answers1

5

Try it — it does work. Svelte doesn't set the attribute when it sees something like autofocus='{{xyz}}, it sets the property — the attribute must be a string (which is unhelpful) whereas the property can be a boolean.

Rich Harris
  • 28,091
  • 3
  • 84
  • 99
  • Excellent, that covers [Boolean html5 attributes](https://www.w3.org/TR/html5/infrastructure.html#boolean-attributes) defined in html, as you explain in https://github.com/sveltejs/svelte/issues/301. My use case is solved by that. – dschulten Aug 18 '17 at 11:10
  • But there is a related question: how about [String attributes](https://svelte.technology/repl?version=1.30.0&gist=d3c9e949965b10d276f429cfa8aea82b) – dschulten Aug 18 '17 at 11:31
  • Currently, that's not possible. We haven't yet encountered a situation where it's a problem (as opposed to a theoretical concern), but if it's causing a bug in your app, please raise an issue! – Rich Harris Aug 18 '17 at 14:54