In Angular 2+ (for example), I can use this syntax to disable a field conditionally:
<input [disabled]="booleanCondition" type="text">
In Svelte I'm trying to do as follows, but it doesn't work:
<input {booleanCondition ? 'disabled=""' : ''} type="text">
How can I do it?
Like this:
<input disabled={booleanCondition}>
<script>
let disabled = true;
</script>
<input {disabled} type="text"/>
This is the shorthand for:
<script>
let disabled = true;
</script>
<input disabled={disabled} type="text"/>
It works because when the attribute name and value match (name={name}), they can be replaced with {name}.
You can find this at Svelte Docs
Works the same in a button:
<button {disabled}>Can't Click</button>
I'd add to the accepted answer, that one can pass an external (with respect to the component) boolean value as follows:
<!-- Nested.svelte -->
<input disabled={ $$props.disabled }>
<!-- App.svelte -->
<Nested disabled={ booleanCondition }/>
To generalize the approach:
<!-- Nested.svelte -->
<script>
const { type, name, required, disabled } = $$props
</script>
<input { type } { name } { required } { disabled }>
<!-- App.svelte -->
<Nested type="text" name="myName" required disabled={ booleanCondition }/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With