Is it possible to bind object field directly in Svelte 3?

5.9k views Asked by At

Is there a way to bind object field in Svelte 3?

Example:

<script>
  import MyComponent from "./MyComponent.svelte"
  let myobjectID
</script>

<MyComponent bind:myobject[id]={myobjectID}>

<!-- Where myobject == {id: "123", name: "myName", and so on...} -->

Is this possible?

2

There are 2 answers

0
Stephane Vanraes On

No there isn't.

If you want MyComponent to work internally with an object, but only allow the consumer to change a specific part of that object you could do as follows:

App.svelte

<script>
  import MyComponent from "./MyComponent.svelte"
  let myobjectID
</script>

<MyComponent bind:id={myobjectID} />

MyComponent.svelte

<script>
    export let id
    $: myobject = {
        id,
        name: 'myName'
    }
</script>

But a more generic way where you would be able to do this way any property of myobject does not exist, in that case you're better off not using an object internally for your component and just constructing it as an object when you need it.

0
Chagai Wild On

There's no built-in way in svelte to do that, but here's a workaround:

<script>
    import MyComponent from './MyComponent.svelte';
    let myobjectID = 1;
    $: myObject = {...myObject, id: myobjectID}
</script>
<MyComponent bind:myobject={myObject} />

The solution is to create a reactive statement that takes all myobject properties and assign them to myObject local variable in the App.svelte, and assign the id property afterwards, which then will bind to the myobject and have it changes as myobjectID changes.