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:
<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.