hatellla
hatellla

Reputation: 5142

Component inside another Component in svelte

I have written the following component in svelte.

DataTableTest.svelte

<script>
  export let title;
  export let data;
  export let columns = [];
</script>

{title}
<table>
  {#if columns}
    <tr>
      {#each columns as c}
        <td>{c.label}</td>
      {/each}
    </tr>
  {/if}
  {#if data}
    <tbody>
      {#each data as d, i}
        <tr>
          {#each columns as c}
              <td>
              {@html d[c.property] ? d[c.property] : ''}
              </td>
          {/each}
        </tr>
      {/each}
    </tbody>
  {/if}
</table>

Now, I wanted to create this component, but within that, I again want to use the same component, something like below:

import DataTableTest from "./DataTableTest.svelte";

let columns = [
    {
      label: "ABC",
      property: "abc"
    },
    {
      label: "Items",
      property: "items"
    }
  ];


let data = [
  {
    "abc": "dsaaads",
    "items": "<DataTableTest title=\"dsaadsa\">",
  }

</script>


<DataTableTest title="Test" {data} {columns} />

But this line,

<DataTableTest title=\"dsaadsa\">

is not doing anything. If instead of DataTableTest, I used normal tags of html like div, etc., it works fine.

Upvotes: 2

Views: 3471

Answers (1)

Morphyish
Morphyish

Reputation: 4072

Afaik, you can't use svelte component inside the @html template.

However you could probably achieve something using svelte:component.

I made you a small example to demonstrate how to use it here

but basically you need to pass the element constructor inside your data structure and then instantiate it with the svelte:component element by passing the constructor of the custom element to the this prop.

<script>
    import DataSet from './DataSet.svelte'
    export let data;
</script>

<DataSet {data} />
<script>
    export let component; // pass the DataSet constructor to your component as prop here
    export let data;
</script>

<!-- your component here -->
<svelte:component this={component} {data} />

Upvotes: 4

Related Questions