Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable field conditionally in Svelte?

Tags:

html

svelte

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 image 587
Claudio Holanda Avatar asked May 15 '18 14:05

Claudio Holanda


3 Answers

Like this:

<input disabled={booleanCondition}>
like image 172
Rich Harris Avatar answered Nov 13 '22 00:11

Rich Harris


<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>
like image 33
lluistar Avatar answered Nov 12 '22 23:11

lluistar


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 }/>
like image 3
Dmitry Avatar answered Nov 13 '22 01:11

Dmitry