Skip to content
IzzyBlazor

Enter all results ↑ ↓ move Esc close

Autocomplete

Since 0.1.0-alpha.21
Suggests as the user types, and takes any text.

An autocomplete is a text field that suggests as the user types. Whatever is typed is the value; a suggestion only fills it in. When the value must be one of the options, use a Combobox.

Suggestions from a list

An autocomplete binds to a string. Set Items to the suggestions. Typing shows the ones that contain the text, ignoring case and accents, and the list opens only when something matches.

Static

Preview

Amsterdam
Athens
Barcelona
Berlin
Brussels
Budapest
Copenhagen
Dublin
Edinburgh
Florence
Helsinki
Istanbul
Kraków
Lisbon
London
Madrid
Milan
Munich
Oslo
Paris
Porto
Prague
Reykjavík
Rome
Seville
Stockholm
Tallinn
Valencia
Venice
Vienna
Warsaw
Zürich

Pick one, or type a city that isn't listed.

Code

Usage.razor
@using System.ComponentModel.DataAnnotations

<Form Model="Model" FormName="autocomplete-usage" OnValidSubmit="Save" MaxWidth="24.Rem" Grow>
    <Autocomplete @bind-Value="Model!.City" Items="CityNames" Placeholder="Start typing a city"
                  Hint="Pick one, or type a city that isn't listed." />
    <Row><Button Submit>Save</Button></Row>
    @if (_saved is { } saved)
    {
        <Alert Status="Status.Success">Saved: @(saved.Length == 0 ? "no city" : saved).</Alert>
    }
</Form>

@code {
    [SupplyParameterFromForm(FormName = "autocomplete-usage")]
    private Trip? Model { get; set; }

    // What was saved, not the field: on an interactive page it follows each change.
    private string? _saved;

    protected override void OnInitialized() => Model ??= new();

    private void Save() => _saved = Model!.City?.Trim() ?? "";

    public sealed class Trip
    {
        [Display(Name = "City"), StringLength(80)]
        public string? City { get; set; }
    }

    private static readonly string[] CityNames =
    [
        "Amsterdam", "Athens", "Barcelona", "Berlin", "Brussels", "Budapest", "Copenhagen", "Dublin",
        "Edinburgh", "Florence", "Helsinki", "Istanbul", "Kraków", "Lisbon", "London", "Madrid",
        "Milan", "Munich", "Oslo", "Paris", "Porto", "Prague", "Reykjavík", "Rome", "Seville",
        "Stockholm", "Tallinn", "Valencia", "Venice", "Vienna", "Warsaw", "Zürich",
    ];
}

Static: IzzyBlazor's script narrows the suggestions in the browser as you type, ignoring case and accents: "krak" finds Kraków.

Add this example to a page with the izzy CLI:

bash
izzy add component Autocomplete --at <file>:<line>

The value is free text, so validate it like any text field, such as with [StringLength]. Before trusting a posted value, see Values a form post can change.

Suggestions from a provider

For suggestions too many to send whole, set ItemsProvider. It has the signature a Table's or DataGrid's takes: the request's Search is the typed text, and its Take is MaxSuggestions (50 by default). request.ToResult applies both to a query of strings, and ToResultAsync does it through EF Core.

Static

Preview

Alto Cabinet, ash
Alto Cabinet, brass
Alto Cabinet, linen
Alto Cabinet, marble
Alto Cabinet, oak
Alto Cabinet, pine
Alto Cabinet, rattan
Alto Cabinet, steel

Code

Provider.razor
@using System.ComponentModel.DataAnnotations

<Form Model="Model" FormName="autocomplete-provider" MaxWidth="24.Rem" Grow>
    <Autocomplete @bind-Value="Model!.Product" ItemsProvider="FindProducts" MaxSuggestions="8"
                  Placeholder="Search 400 products" />
</Form>

@code {
    [SupplyParameterFromForm(FormName = "autocomplete-provider")]
    private Order? Model { get; set; }

    protected override void OnInitialized() => Model ??= new();

    // The same signature as a Table's or DataGrid's ItemsProvider. request.Search is the typed
    // text and request.Take is MaxSuggestions; ToResult applies both to a query of strings. Against
    // a database: request.ToResultAsync(db.Products.Select(p => p.Name).OrderBy(n => n), ...).
    private ValueTask<DataResult<string>> FindProducts(DataRequest<string> request) =>
        ValueTask.FromResult(request.ToResult(Products.AsQueryable().OrderBy(name => name)));

    public sealed class Order
    {
        [Display(Name = "Product")]
        public string? Product { get; set; }
    }

    private static readonly string[] Kinds = ["Chair", "Desk", "Lamp", "Shelf", "Sofa", "Rug", "Table", "Stool", "Cabinet", "Mirror"];
    private static readonly string[] Finishes = ["oak", "walnut", "ash", "pine", "steel", "brass", "linen", "velvet", "marble", "rattan"];
    private static readonly string[] Lines = ["Fjord", "Mesa", "Alto", "Nova"];

    private static readonly string[] Products =
        [.. from line in Lines from kind in Kinds from finish in Finishes select $"{line} {kind}, {finish}"];
}

Static: The provider fills the list once with the first eight, and typing filters those in the browser.

Against a database:

csharp
private async ValueTask<DataResult<string>> FindProducts(DataRequest<string> request) =>
    await request.ToResultAsync(db.Products.Select(p => p.Name).OrderBy(n => n),
        count: (q, ct) => q.CountAsync(ct),
        list: (q, ct) => q.ToListAsync(ct));

For a plain method instead, set Search, as on Combobox: it receives the typed text and returns the suggestions. Either way, the field asks after each pause in typing (Debounce, 250 ms by default). On a static page, each pause fetches the page with the typed text in its URL; see Searching a long list on Combobox for what that render sees.

Keys

Typing doesn't highlight a suggestion, so Enter keeps what was typed and submits the form. Down and Up move through the suggestions, Enter takes the highlighted one, and Escape closes the list without changing the text.

Without JavaScript

With JavaScript off, the field is a text input with the browser's own suggestions (a datalist). It posts whatever is typed. The browser styles that list, and not every screen reader announces it.

Mode support

What works in each mode, Autocomplete
FeatureStaticInteractive
Any typed text is the value, posted with the formYesYes
Typing narrows the suggestions in the browser, ignoring case and accentsYesYes
Search or ItemsProvider fills the suggestions when the page loadsYesYes
Each pause in typing asks Search or ItemsProvider for new suggestionsNoYes

Static: static server-side rendering, with no circuit and no WebAssembly. Interactive: Server, WebAssembly or Auto.

Accessibility

  • The input is a combobox with a listbox of suggestions: focus stays in the input, and the highlighted suggestion is its aria-activedescendant.
  • Typing doesn't highlight a suggestion, so Enter keeps what was typed (and submits the form). Down and Up move through the suggestions, Enter takes one, and Escape closes the list without changing the text.
  • The list opens only when something matches. A change in how many suggestions it shows is announced politely ("3 options available.", IzzyText.OptionsAvailable).
  • With JavaScript off, the browser shows its own suggestions (a datalist); not every screen reader announces them.

Keyboard navigation

In the field

Autocomplete keys, In the field
Press this keyTo do this
DownOpen the suggestions at the first; in the open list, go to the next
UpOpen the suggestions at the last; in the open list, go to the previous
Alt+DownOpen the suggestions without highlighting one
Alt+UpTake the highlighted suggestion and close the list
Page Down or Page UpMove ten suggestions
EnterTake the highlighted suggestion; with none highlighted, keep the typed text and submit the form
EscapeClose the list, leaving the text as it is
TabClose the list and move on

Parameters

Autocomplete parameters
PropTypeDefault
ItemsSuggestions, narrowed in the browser as the user types.IEnumerable<string>?
SearchFinds suggestions for the typed text, for lists too long to send whole.Func<string, CancellationToken, Task<IEnumerable<string>>>?
ItemsProviderFinds suggestions with the provider signature Table and DataGrid use: the request's Search is the typed text and its Take is MaxSuggestions, and request.ToResult(query) (or ToResultAsync, through EF Core) applies both to a query of strings.Func<DataRequest<string>, ValueTask<DataResult<string>>>?
MaxSuggestionsThe most suggestions ItemsProvider is asked for (its request's Take).int50
DebounceHow long to wait after the last keystroke before searching.TimeSpanTimeSpan.FromMilliseconds(250)
PlaceholderText in the empty field, such as "Start typing a city".string?
ClearableA button in the field that empties it, there while it holds text.boolfalse
ReadOnlyMakes the field read-only: the text shows in a read-only text field, and the value still posts.boolfalse
@bind-ValueThe value, bound with @bind-Value.string?
DisplayNameThe field's name in validation messages from the input itself, such as a value that can't be parsed.string?

See also

  • Combobox: lets the user type to filter a list of options, with server search on interactive pages.
  • TextField: lets the user enter a line of text, with a label, add-ons and masks.

Connection lost

Rejoining the server…