Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sveltejs render html attribute conditionally

Tags:

svelte

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

like image 805
dschulten Avatar asked Aug 16 '17 13:08

dschulten


1 Answers

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.

like image 84
Rich Harris Avatar answered Nov 19 '22 08:11

Rich Harris