How to bind input value from child component in Svelte?
Asked Answered
H

1

6

ideal

I'd like to get input data from child component.

What I have tried

<script>
  import Input from "./Input.svelte";
  let userGoal = "";
</script>

<h1>Your Goal is {userGoal}</h1>

<Input {userGoal} />
<script>
  export let userGoal = "";

  $: console.log(userGoal);
</script>

<input type="text" bind:value={userGoal} />

$: console.log(userGoal); shows userGoal at each event which is as I expected. However, It doesn't affect to parent Component.

Summary

I'm new to Svelte. Any help is appreciated.

Haleigh answered 30/11, 2019 at 19:49 Comment(0)
J
16

Just change <Input {userGoal}/> to this:

<Input bind:userGoal/>

Demo here. If you want to call it something else in the parent, do bind:userGoal={somethingElse}.

Here's a tutorial on component bindings.

Justiciable answered 30/11, 2019 at 21:0 Comment(2)
Wow, great. Thank you very much. I have an another question, but why it's different way from "parent to child"? When trying pass input value to child, I didn't need to write bind.Haleigh
Because normally data should flow from parents to children. Flowing from children to parents should be the exception, used sparingly.Justiciable

© 2022 - 2024 — McMap. All rights reserved.