Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access properties on a dynamically created component in Svelte

How can I access a component’s properties when that component was created dynamically at runtime? When creating a component in markup I can simply bind:someProperty={someVariable}, but I don’t know of any way to do this when the component is instantiated using new Component() at runtime? How can I get access to this new component’s properties?

App.svelte:

<script>
    import { onMount } from "svelte";
    
    import Component2 from "./Component2.svelte";
    
    let taken;
    
    let container;
    
    onMount(() => {
        new Component2({
            target: container
        });
        
        // How do I access this new component's `someValue` property?
    });
    
</script>

<div bind:this={container}>
    
</div>

<Component2 bind:someValue={taken}></Component2>

Component2.svelte:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<script>
    export const someValue = Math.floor(Math.random() * 8999 + 1000);
</script>

<p>
    {someValue}
</p>

I know that I can pass in a props: {} object to the constructor to assign values to the properties, but what I want is to have the component assign its own values to the properties and just be able to access them from outside the component.

Is this considered bad practice and a "not Svelte-like" approach? Should I be using a store instead? If so, what should that look like?

>Solution :

You cannot use bindings in code, but you can read the values given that you set an option in the component. Add this to the component file:

<svelte:options accessors />

That way you can store the reference and access the property:

const component = new Component2({
    target: container
});

const value = component.someValue;

As for whether this is a good idea, I would only construct components in code when there is a good reason to. E.g. it may makes sense for a modal dialog that is added temporarily and whose state is disposed of after use anyway.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading