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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Excellent, that covers Boolean html5 attributes defined in html, as you explain in github.com/sveltejs/svelte/issues/301. My use case is solved by that.
But there is a related question: how about String attributes
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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.