I have a custom <MyInput />
component like this:
<script lang="ts">
//=== MyInput.svelte ===
type Props = {
input: HTMLInputElement
value: string
}
let { input = $bindable(), value = $bindable() }: Props = $props()
</script>
<input bind:this={input} bind:value />
I want to be able to programmatically blur this field from a parent component wherever it is used.
<script lang="ts">
//=== Parent.svelte ===
import MyInput from '$lib/MyInput.svelte'
let input: HTMLInputElement
function blurField(){
input.blur() <!-- console error
}
</script>
<MyInput {input} {value} />
<button onclick={() => blurField()}>Blur Field</button>
I'm unclear on how to bind my reference to the input
in the parent to the actual child component. It doesn't appear to actually have connected the input
in the parent to the binding of the child.
Any ideas what I'm doing wrong?
You have to bind:
the component's input at the very least:
<MyInput bind:input {value} />
(Without it, values would only be passed down.)