Component Methods (Imperative API)

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.

Live Demo

Use the buttons below to interact with the component instance directly.

Methods Reference

The following methods are available on the component instance.

clear()
Clears the text input, removes suggestions, and resets the session token.
() => void
focus()
Sets focus on the text input field.
() => void
getRequestParams()
Returns the current internal `requestParams` object being used for API calls.
() => RequestParams

Full Code Example

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>

2025 Places Autocomplete Svelte.