[Svelet FAQs] Binding Frequently Asked Questions (FAQs)
Binding FAQs
Sometimes it’s useful to break that rule. Take the case of the <input>
element in this component — we could add an on:input event handler that sets the value of name to event.target.value, but it’s a bit… boilerplatey. It gets even worse with other form elements, as we’ll see.
Instead, we can use the bind:value directive:
1 | <input bind:value={name}> |
This means that not only will changes to the value of name update the input value, but changes to the input value will update name.
See bind:property | API Docs • Svelte - https://svelte.dev/docs#bind_element_property to learn more.
A child component modify a variable/object on its parent
1 | <!-- scr/lib/components/TextField.svelte --> |
1 | <!-- src/app.svelte --> |
See svelte: how can a component modify a variable/object on its parent? - Stack Overflow - https://stackoverflow.com/questions/62841384/svelte-how-can-a-component-modify-a-variable-object-on-its-parent, How to pass input value from child component to parent component - https://linguinecode.com/post/pass-input-value-from-child-component-to-parent-component to learn more.
‘type’ attribute cannot be dynamic if input uses two-way binding
1 | <input class="mdc-text-field__input" {type} aria-labelledby={id_or_name} bind:value /> |
Replace {type}
with use:ref
to fix that issue.
1 | <script lang="ts"> |
See svelte - error: ‘type’ attribute cannot be dynamic if input uses two-way binding - Stack Overflow - https://stackoverflow.com/questions/57392773/error-type-attribute-cannot-be-dynamic-if-input-uses-two-way-binding, use:action | API Docs • Svelte - https://svelte.dev/docs#use_action to learn more.
References
[1] use:action | API Docs • Svelte - https://svelte.dev/docs#use_action
[2] bind:property | API Docs • Svelte - https://svelte.dev/docs#bind_element_property
[3] SvelteKit • The fastest way to build Svelte apps - https://kit.svelte.dev/
[4] Svelte • Cybernetically enhanced web apps - https://svelte.dev/