pstanoev / simple-svelte-autocomplete

Simple Autocomplete / typeahead component for Svelte
http://simple-svelte-autocomplete.surge.sh/
MIT License
464 stars 78 forks source link

How to use a non-label field as the input value after selecting #213

Open ricochenft opened 1 year ago

ricochenft commented 1 year ago

With the following code from README.md, when selecting from the dropdown, the text from name would populate the input value. What if I want the input field to show code instead?

const colorList = [
  { id: 1, name: "White", code: "#FFFFFF" },
  { id: 2, name: "Red", code: "#FF0000" },
  { id: 3, name: "Yellow", code: "#FF00FF" },
  { id: 4, name: "Green", code: "#00FF00" },
  { id: 5, name: "Blue", code: "#0000FF" },
  { id: 6, name: "Black", code: "#000000" },
]

let selectedColorObject
<AutoComplete items={colorList} bind:selectedItem={selectedColorObject} labelFieldName="name" />

I can somewhat get it working by this hack-ish way:

<AutoComplete
    items={colorList}
    bind:selectedItem={selectedColorObject}
    labelFieldName="code"
>
    <div slot="item" let:item>
        <span>{item.name}</span>
    </div>
</AutoComplete>

But that workaround creates two new problems: