Blazorise Autocomplete component
The Autocomplete
component offers simple and flexible type-ahead functionality.
The Autocomplete
component provides suggestions while you type into the field. The component is in essence
a text box which, at runtime, filters data in a drop-down by a Filter
operator when a user captures a value.
You may also enable FreeTyping
and Autocomplete
can be used to just provide suggestions based on user input.
Quick Installation
Blazorise.Components
NuGet package.
Step 1: Download from NuGet
Install extension from NuGet:Install-Package Blazorise.Components
Step 2. Define Usings
In your main_Imports.razor
add:
@using Blazorise.Components
Examples
Searching single value
<Autocomplete TItem="Country" TValue="string" Data="" TextField="@(( item ) => item.Name)" ValueField="@(( item ) => item.Iso)" @bind-SelectedValue="" @bind-SelectedText="selectedAutoCompleteText" Placeholder="Search..." Filter="AutocompleteFilter.StartsWith" FreeTyping CustomFilter="@(( item, searchValue ) => item.Name.IndexOf( searchValue, 0, StringComparison.CurrentCultureIgnoreCase ) >= 0 )"> <NotFoundContent> Sorry... @context was not found! :( </NotFoundContent> </Autocomplete> <Field Horizontal> <FieldBody ColumnSize="ColumnSize.Is12"> Selected search value: @selectedSearchValue </FieldBody> <FieldBody ColumnSize="ColumnSize.Is12"> Selected text value: @selectedAutoCompleteText </FieldBody> </Field>
@code { [Inject] public CountryData CountryData { get; set; } public IEnumerable<Country> Countries; protected override async Task OnInitializedAsync() { Countries = await CountryData.GetDataAsync(); await base.OnInitializedAsync(); } public string selectedSearchValue { get; set; } public string selectedAutoCompleteText { get; set; } }
Searching multiple values
<Autocomplete TItem="Country" TValue="string" Data="" TextField="@(( item ) => item.Name)" ValueField="@(( item ) => item.Iso)" Placeholder="Search..." SelectionMode="AutocompleteSelectionMode.Multiple" FreeTyping @bind-SelectedValues="multipleSelectionData" @bind-SelectedTexts="multipleSelectionTexts"> </Autocomplete> <Field Horizontal> <FieldBody ColumnSize="ColumnSize.Is12"> Selected Values: @string.Join(',', multipleSelectionData) </FieldBody> <FieldBody ColumnSize="ColumnSize.Is12"> Selected Texts: @(multipleSelectionTexts == null ? null : string.Join(',', multipleSelectionTexts)) </FieldBody> </Field>
@code { [Inject] public CountryData CountryData { get; set; } public IEnumerable<Country> Countries; protected override async Task OnInitializedAsync() { Countries = await CountryData.GetDataAsync(); multipleSelectionData = new List<string>() { Countries.ElementAt( 1 ).Iso, Countries.ElementAt( 3 ).Iso }; await base.OnInitializedAsync(); } List<string> multipleSelectionData; List<string> multipleSelectionTexts; }
Searching with data on demand (ReadData)
Frequently, you'll want to read data on demand rather than loading everything into memory at startup. You can do it with theReadData
API.
It will provide you with enough information for you to call an external data-source, which will return new data, which you can then reassign to the Data
parameter.
CancellationToken
before commiting your values to Data
. This will make sure to avoid race conditions and keep your Data
updated according to the user's last key stroke.
<Autocomplete TItem="Country" TValue="string" Data="" ReadData="" TextField="@(( item ) => item.Name)" ValueField="@(( item ) => item.Iso)" @bind-SelectedValue="" @bind-SelectedText="selectedAutoCompleteText" Placeholder="Search..." FreeTyping> <NotFoundContent> Sorry... @context was not found! :( </NotFoundContent> </Autocomplete> <Field Horizontal> <FieldBody ColumnSize="ColumnSize.Is12"> Selected search value: @selectedSearchValue </FieldBody> <FieldBody ColumnSize="ColumnSize.Is12"> Selected text value: @selectedAutoCompleteText </FieldBody> </Field>
@code { [Inject] public CountryData CountryData { get; set; } public IEnumerable<Country> Countries; public IEnumerable<Country> ReadDataCountries; private Random random = new(); public string selectedSearchValue { get; set; } public string selectedAutoCompleteText { get; set; } protected override async Task OnInitializedAsync() { Countries = await CountryData.GetDataAsync(); await base.OnInitializedAsync(); } private async Task OnHandleReadData( AutocompleteReadDataEventArgs autocompleteReadDataEventArgs ) { if ( !autocompleteReadDataEventArgs.CancellationToken.IsCancellationRequested ) { await Task.Delay( random.Next( 100 ) ); if ( !autocompleteReadDataEventArgs.CancellationToken.IsCancellationRequested ) { ReadDataCountries = Countries.Where( x => x.Name.StartsWith( autocompleteReadDataEventArgs.SearchValue, StringComparison.InvariantCultureIgnoreCase ) ); } } } }
Extending with custom item content
Customize the way you display the Autocomplete items by providingItemContent
.
<Autocomplete TItem="Country" TValue="string" Data="" TextField="@(( item ) => item.Name)" ValueField="@(( item ) => item.Iso)" @bind-SelectedValue="" @bind-SelectedText="selectedAutoCompleteText" Placeholder="Search..." Filter="AutocompleteFilter.StartsWith" FreeTyping CustomFilter="@(( item, searchValue ) => item.Name.IndexOf( searchValue, 0, StringComparison.CurrentCultureIgnoreCase ) >= 0 )"> <NotFoundContent> Sorry... @context was not found! :( </NotFoundContent> <ItemContent> <Div Flex="Flex.InlineFlex.JustifyContent.Between" Width="Width.Is100"> <Heading Margin="Margin.Is2.FromBottom">@context.Value</Heading> <Small>@context.Item.Capital</Small> </Div> <Paragraph Margin="Margin.Is2.FromBottom">@context.Text</Paragraph> </ItemContent> </Autocomplete> <Field Horizontal> <FieldBody ColumnSize="ColumnSize.Is12"> Selected search value: @selectedSearchValue </FieldBody> <FieldBody ColumnSize="ColumnSize.Is12"> Selected text value: @selectedAutoCompleteText </FieldBody> </Field>
@code { [Inject] public CountryData CountryData { get; set; } public IEnumerable<Country> Countries; protected override async Task OnInitializedAsync() { Countries = await CountryData.GetDataAsync(); await base.OnInitializedAsync(); } string selectedSearchValue { get; set; } string selectedAutoCompleteText { get; set; } }
Suggesting already selected items && Checkbox support
You can useSuggestSelectedItems
to suggest already selected items, and optionally use SuggestMultipleCheckbox
to additionally add checkbox selection.
Note: Make sure to set CloseOnSelection
to false if you want to keep the dropdown open whenever an item is selected.
<Autocomplete TItem="Country" TValue="string" Data="" TextField="@(( item ) => item.Name)" ValueField="@(( item ) => item.Iso)" Placeholder="Search..." SelectionMode="AutocompleteSelectionMode.Checkbox" CloseOnSelection="false" @bind-SelectedValues="multipleSelectionData" @bind-SelectedTexts="multipleSelectionTexts"> </Autocomplete> <Field Horizontal> <FieldBody ColumnSize="ColumnSize.Is12"> Selected Values: @string.Join(',', multipleSelectionData) </FieldBody> <FieldBody ColumnSize="ColumnSize.Is12"> Selected Texts: @(multipleSelectionTexts == null ? null : string.Join(',', multipleSelectionTexts)) </FieldBody> </Field>
@code { [Inject] public CountryData CountryData { get; set; } public IEnumerable<Country> Countries; protected override async Task OnInitializedAsync() { Countries = await CountryData.GetDataAsync(); multipleSelectionData = new List<string>() { Countries.ElementAt( 1 ).Iso, Countries.ElementAt( 3 ).Iso }; await base.OnInitializedAsync(); } List<string> multipleSelectionData; List<string> multipleSelectionTexts; }
Highlight search text
AutocompleteHighlightSearch
is a feature that allows you to highlight the search text that you have entered in a dropdown list of items. When you start typing in the search field, the dropdown list of items will automatically be filtered to show only the items that match the search text. The search text will also be highlighted in the dropdown list of items, so that you can easily see which items match your search. This can be a useful feature when you are trying to find a specific item in a long list of items, as it allows you to quickly locate the item you are looking for.
<Autocomplete TItem="Country" TValue="string" Data="" TextField="@(( item ) => item.Name)" ValueField="@(( item ) => item.Iso)" Placeholder="Search..." HighlightSearch> <NotFoundContent> Sorry... @context was not found! :( </NotFoundContent> </Autocomplete>
@code { [Inject] public CountryData CountryData { get; set; } public IEnumerable<Country> Countries; protected override async Task OnInitializedAsync() { Countries = await CountryData.GetDataAsync(); await base.OnInitializedAsync(); } }
Virtualize
Blazorise Autocomplete's Virtualize feature allows for loading data on demand while scrolling, which improves the performance of the component when working with large datasets. With Virtualize, the Autocomplete component only loads the items that are currently visible in the list, and as the user scrolls, more items are loaded in the background. This allows for a much faster and smoother user experience, especially when working with large lists of items.
This feature can be easily enabled by setting the Virtualize
property to "true"
on the Autocomplete component.
<Autocomplete TItem="Country" TValue="string" Data="" TextField="@(( item ) => item.Name)" ValueField="@((item) => item.Iso)" @bind-SelectedValue="selectedSearchValue" Placeholder="Search..." Virtualize> <NotFoundContent> Sorry... @context was not found! :( </NotFoundContent> </Autocomplete>
@code { [Inject] public CountryData CountryData { get; set; } public IEnumerable<Country> Countries; protected override async Task OnInitializedAsync() { Countries = await CountryData.GetDataAsync(); await base.OnInitializedAsync(); } public string selectedSearchValue { get; set; } }
API
Attributes
Name | Description | Type | Default |
---|---|---|---|
TItem |
Model data type. | generic |
|
Data |
Data used for the search. | IEnumerable<TItem> |
|
TextField |
Selector for the display name field. | Func |
|
ValueField |
Selector for the value field. | Func |
|
SelectedValue |
Currently selected value. | object |
|
SelectedValueChanged |
Raises an event after the selected value has changed. | EventCallback<string> |
|
SelectedText |
Currently selected text. | string |
|
SelectedTextChanged |
Raises an event after the selected text has changed. | EventCallback<string> |
|
CurrentSearch |
Gets or sets the currently selected item text. CurrentSearch is deprecated and will be removed in a future version, please use Search instead. | string |
|
CurrentSearchChanged |
Occurs on every search text change. CurrentSearchChanged is deprecated and will be removed in a future version, please use SearchChanged instead. | EventCallback<string> |
|
Search |
Gets or sets the currently selected item text. | string |
|
SearchChanged |
Occurs on every search text change. | EventCallback<string> |
|
Placeholder |
Placeholder for the empty search field. | string |
|
MinLength |
Minimum number of character needed to start search. Set this to 0 to make the Autocomplete function like a dropdown. | int |
1 |
MaxMenuHeight |
Sets the maximum height of the dropdown menu. | string |
200px |
Filter |
Filter method used to search the data. | enum |
StartsWith |
Disabled |
Disable the input field. | bool |
false |
Immediate |
If true the text in will be changed after each key press (overrides global settings). | bool? |
null |
Debounce |
If true the entered text will be slightly delayed before submitting it to the internal value. | bool? |
null |
DebounceInterval |
Interval in milliseconds that entered text will be delayed from submitting to the internal value. | int? |
null |
Validator |
Validation handler used to validate selected value. | Action<ValidatorEventArgs> |
null |
AsyncValidator |
Asynchronously validates the selected value. | Func<ValidatorEventArgs, CancellationToken, Task> |
null |
NotFoundContent |
Render fragment when no value has been found on the data source. | RenderFragment<string> |
|
NotFound |
Raises an event when no value has been found on the data source. | EventCallback<string> |
|
FreeTyping |
Allows the value to not be on the data source. | bool |
false |
CustomFilter |
Handler for custom filtering on Autocomplete’s data source. | Func<TItem, string, bool> |
|
Multiple |
Allows for multiple selection. Multiple parameter will be removed in a future version, please replace with SelectionMode.Multiple Parameter instead. | bool |
false |
MultipleBadgeColor |
Sets the Badge color for the multiple selection values. Used when multiple selection is set. | Color |
Color.Primary |
MultipleDisabledBadgeColor |
Sets the disabled Badge color for the multiple selection values. Used when multiple selection is set. | Color |
Color.Light |
SelectedValues |
Currently selected items values. | List<TValue> |
|
SelectedValuesChanged |
Occurs after the selected values have changed. | EventCallback<List<TValue>> |
|
SelectedTexts |
Currently selected items texts. | List<string> |
|
SelectedTextsChanged |
Occurs after the selected texts have changed. | EventCallback<List<string>> |
|
ItemContent |
Specifies the item content to be rendered inside each dropdown item. | RenderFragment<ItemContext<TItem,TValue>> |
|
CloseOnSelection |
Specifies whether Autocomplete's dropdown closes on selection. This is only evaluated when multiple selection is set. Defauls to true. | bool |
true |
ReadData |
Event handler used to load data manually by based on the current search value. | EventCallback<AutoCompleteReadDataEventArgs> |
|
SuggestSelectedItems |
Suggests already selected option(s) when presenting the options. | bool |
false |
ConfirmKey |
Gets or sets an array of the keyboard pressed values for the ConfirmKey. If this is null or empty, there will be no confirmation key. | string[] |
new[] { "Enter", "NumpadEnter" } |
AutoPreSelect |
Gets or sets whether Autocomplete auto preselects the first item when the drop down opens. | bool |
true |
AutoSelectFirstItem |
Gets or sets whether Autocomplete auto preselects the first item from the data list on initialization. This overrides initial SelectedValue. | bool |
false |
SelectionMode |
Gets or sets the Autocomplete Selection Mode. | AutocompleteSelectionMode |
AutocompleteSelectionMode.Default |
HighlightSearch |
If true, the searched text will be highlighted in the dropdown list items based on Search value.
|
bool |
false |
SearchBackground |
Defines the background color of the search field. | Background |
null |
SearchTextColor |
Defines the text color of the search field. | TextColor |
null |
Closed |
Event handler used to detect when the autocomplete is closed. | EventCallback<AutocompleteClosedEventArgs> |
|
Opened |
Event handler used to detect when the autocomplete is opened. | EventCallback |
|
FreeTypingNotFoundTemplate |
Specifies the not found content to be rendered when no data is found and FreeTyping is enabled. | RenderFragment<string> |
Methods
Name | Description | Type | Default |
---|---|---|---|
ScrollItemIntoView |
Scrolls an item into view. | ||
Reload |
Triggers the reload of the Autocomplete data. Makes sure not to reload if the Autocomplete is in a loading state. | ||
AddMultipleTextAndValue |
Adds a Multiple Selection. | ||
RemoveMultipleTextAndValue |
Removes a Multiple Selection. | ||
Clear |
Clears the selected value and the search field. | ||
ResetSelected |
Clears the current selection. | ||
OpenDropdown |
Opens the Autocomplete Dropdown. | ||
Close |
Closes the Autocomplete Dropdown. | ||
IsSelectedvalue |
Gets whether the TValue is selected. | ||
IsSelectedItem |
Gets whether the TItem is selected. | ||
GetItemByValue |
Gets a TItem from Data by using the provided ValueField.
|
||
GetItemByText |
Gets a TItem from Data by using the provided TextField.
|
||
IsSafeToClose |
IsSafeToClose is deprecated. This API now always returns true. | ||
MaxEntryLength |
Specifies the maximum number of characters allowed in the input element. | ||
Virtualize |
Gets or sets whether the Autocomplete will use the Virtualize functionality.
|
bool |
false |
TagTemplate |
Specifies the badge content to be rendered for each tag (multiple selected item). | RenderFragment<AutocompleteTagContext<TItem, TValue>> |
|
SearchTextChanged |
Occurs after the search box text has changed. | EventCallback<string> |
|
SearchKeyDown |
Occurs when a key is pressed down while the search box has focus. | EventCallback<KeyboardEventArgs> |
|
SearchFocus |
Occurs when the search box gains or loses focus. | EventCallback<FocusEventArgs> |
|
SearchBlur |
The blur event fires when the search box has lost focus. | EventCallback<FocusEventArgs> |
|
PositionStrategy |
Defines the positioning strategy of the dropdown menu as a 'floating' element. | DropdownPositionStrategy |
Fixed |