There's an easy way to get a reference to an instance of a sub component from the parent scope, as shown in the tutorial.
What I want is to get a reference to the component from within the component itself. So, if we were looking at the official Svelte demo linked above, I would be meaning that I want a reference to the InputField instance from within the InputField instance, rather than from App.svelte.
(The reason I want this: I need instances to fire hooks to external JS libraries that will interract with the instance programmatically.)
App.svelte:
<script>
import InputField from './InputField.svelte';
let field;
</script>
<InputField bind:this={field}/>
<button on:click={() => field.focus()}>Focus field</button>
InputFiled.svelte:
<script>
let input;
export function focus() {
input.focus();
}
// Somewhere here, I want a var, like you might imagine the following to do:
let myself = this;
</script>
<input bind:this={input} />
You can get a refrence from the parent and pass it the child:
<script>
import InputField from './InputField.svelte';
let field;
</script>
<InputField bind:this={field} {field}/>
<button on:click={() => field.focus()}>Focus field</button>
once you get the field pass it to the input
<script>
let input;
export let field;
export function focus() {
input.focus();
}
let myself;
$:if(field) myself = field;
</script>
<input bind:this={input} />
and you can use it with context.
When passing the reference that is set in the parent to the child as a prop it is possible to use it inside the component itself > REPL
<script>
import Component from './Component.svelte';
let reference
</script>
<Component bind:this={reference} {reference}/>
<script>
export let reference;
$: reference && console.log('reference in component', reference)
</script>