How to properly pass an attribute from parent custom element to child custom element?

ParentCustomElement.svelte

<svelte:options tag="parent-custom-element" />

<script>
  import ChildCustomElement from "./ChildCustomElement.svelte";
  let greeting = "Hello";
</script>

<child-custom-element greeting="{greeting}"></child-custom-element>

ChildCustomElement.svelte

<svelte:options tag="child-custom-element" />

<script>
  export let greeting;
  /* within the script scope "greeting" is undefined */
  console.log(greeting);
</script>

<!-- within the template scope "greeting" is defined ("hello") -->
<p>{greeting}</p>

What I need is access to the attribute value within the script scope to do some magic and only after that load the template. How to do this?

>Solution :

You probably can use onMount like this:

<script>
  import { onMount } from 'svelte';

  export let greeting;

  let initialized = false;
  onMount(() => {
    // [use greeting for whatever]

    initialized = true;
  });
</script>

{#if initialized}
  ...
{/if}

Leave a Reply