[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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!-- scr/lib/components/TextField.svelte  -->

<script lang="ts">
export let name;

export let type: 'email' | 'text' | 'password' | 'number' = 'text'

const ref = (node: HTMLInputElement) => {
node.type = type;
}

export let value;
</script>

<input bind:value={value[name]} {name} use:ref />
1
2
3
4
5
6
7
<!-- src/app.svelte -->

<script lang="ts">
import TextField from "$lib/components/TextField.svelte";

<TextField bind:value={account} name="name" />
</script>

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
2
3
4
5
6
7
8
9
10
11
<script lang="ts">
export let type: 'email' | 'text' | 'password' | 'number' = 'text'

const ref = (node: HTMLInputElement) => {
node.type = type;
}

export let value;
</script>

<input class="mdc-text-field__input" use:ref aria-labelledby={id_or_name} bind:value />

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

[2] How to pass input value from child component to parent component - https://linguinecode.com/post/pass-input-value-from-child-component-to-parent-component

[3] SvelteKit • The fastest way to build Svelte apps - https://kit.svelte.dev/

[4] Svelte • Cybernetically enhanced web apps - https://svelte.dev/