While props offer a declarative way to configure the component, there are times when you need
to programmatically control its behavior. For these advanced use cases, you can get a direct
reference to the component instance using Svelte's bind:this
directive.
This imperative approach is useful for tasks like clearing the input from an external button, integrating with form libraries, or calling methods from a parent component.
Use the buttons below to interact with the component instance directly.
The following methods are available on the component instance.
clear()
() => void
focus()
() => void
getRequestParams()
() => RequestParams
The example below shows how to bind to the component instance and call its methods from buttons.
<script lang="ts">
import { PlaceAutocomplete } from 'places-autocomplete-svelte';
import type { PlaceResult, ComponentOptions, RequestParams } from 'places-autocomplete-svelte/interfaces';
let autocompleteComponent: PlaceAutocomplete | undefined = $state(undefined);
// --- Event Handlers ---
const handleResponse = (response: PlaceResult) => {
console.log('Place Selected:', response);
};
const handleError = (error: string) => {
console.error('Places Autocomplete Error:', error);
};
</script>
<PlaceAutocomplete
bind:this={autocompleteComponent}
{PUBLIC_GOOGLE_MAPS_API_KEY}
{onError}
{onResponse}
/>
<div class="controls">
<button onclick={() => autocompleteComponent?.clear()}>Clear</button>
<button onclick={() => autocompleteComponent?.focus()}>Focus Input</button>
<button onclick={() => console.log(JSON.stringify(autocompleteComponent?.getRequestParams(), null, 2))}>
Get Request Params
</button>
</div>