Skip to content
IzzyBlazor

Enter all results ↑ ↓ move Esc close

TreeSelect

Since 0.1.0-alpha.22
Opens a tree from a field, so a choice from a deep hierarchy takes the space of one input.

Choose one item from a tree, such as a category, a team or a folder.

A category

Set Items to the top level and ItemChildren to each item's children. ItemValue is what binds and posts, here an id, and ItemText names each item.

Static

Preview

Code

Usage.razor
@using System.ComponentModel.DataAnnotations

<Form Model="Model" FormName="tree-select-usage" OnValidSubmit="Save" MaxWidth="24.Rem" Grow>
    <TreeSelect @bind-Value="Model!.CategoryId" Items="Categories" ItemChildren="c => c.Children"
                ItemValue="c => c.Id" ItemText="c => c.Name" Placeholder="Choose a category" Searchable Clearable />
    <Row><Button Submit>Save product</Button></Row>
    @if (_saved is not null)
    {
        <Alert Status="Status.Success">Filed under @_saved.</Alert>
    }
</Form>

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

    private string? _saved;

    protected override void OnInitialized() => Model ??= new() { CategoryId = 12 };

    private void Save() => _saved = Find(Categories, Model!.CategoryId)?.Name ?? "no category";

    public sealed class Product
    {
        [Display(Name = "Category")]
        public int? CategoryId { get; set; }
    }

}

Static: Choosing closes the tree and shows the category in the field at once; Save posts it.

Add this example to a page with the izzy CLI:

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

Any item can be chosen, a parent too. The tree opens on the chosen item, and Searchable adds a box that narrows it.

Only the ends of branches

To make parents labels for their branches, return false from ItemSelectable for them. A click on one opens or closes its branch. Here departments group the teams, and a ticket goes to a team.

Static

Preview

Departments group the teams.

Code

Team.razor
@using System.ComponentModel.DataAnnotations

<Form Model="Model" FormName="tree-select-team" OnValidSubmit="Save" MaxWidth="24.Rem" Grow>
    <TreeSelect @bind-Value="Model!.TeamId" Items="Departments" ItemChildren="d => d.Teams"
                ItemValue="d => d.Id" ItemText="d => d.Name" ItemSelectable="d => d.Teams.Length == 0"
                Placeholder="Choose a team" Hint="Departments group the teams." />
    <Row><Button Submit>Assign</Button></Row>
    @if (_saved is not null)
    {
        <Alert Status="Status.Success">Assigned to @_saved.</Alert>
    }
</Form>

@code {
    [SupplyParameterFromForm(FormName = "tree-select-team")]
    private Ticket? Model { get; set; }

    private string? _saved;

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

    private void Save() => _saved = Departments.SelectMany(d => d.Teams).FirstOrDefault(t => t.Id == Model!.TeamId)?.Name;

    public sealed class Ticket
    {
        [Required(ErrorMessage = "Choose a team")]
        [Display(Name = "Team")]
        public string? TeamId { get; set; }
    }

}

Folders that load

For a tree too large to send at once, set ItemHasChildren and ChildrenProvider: the first time a branch opens, the provider gets the item's key and returns its children. A chosen folder in a branch still to load has no item to name it, so ValueText does, here with its path.

Static

Preview

Code

Folders.razor
@using System.ComponentModel.DataAnnotations

<Form Model="Model" FormName="tree-select-folders" OnValidSubmit="Save" MaxWidth="24.Rem" Grow>
    <TreeSelect @bind-Value="Model!.FolderId" Items="Drive.Top" ItemValue="f => f.Id" ItemText="f => f.Name"
                ItemIcon="_ => Lucide.Folder" ItemHasChildren="f => f.HasFolders" ChildrenProvider="LoadFolders"
                ValueText="id => Drive.PathOf(id)" />
    <Row><Button Submit>Save file</Button></Row>
    @if (_saved is not null)
    {
        <Alert Status="Status.Success">Saved to @_saved.</Alert>
    }
</Form>

@code {
    [SupplyParameterFromForm(FormName = "tree-select-folders")]
    private Upload? Model { get; set; }

    private string? _saved;

    // A folder two levels down: its branch hasn't loaded, so ValueText names it.
    protected override void OnInitialized() => Model ??= new() { FolderId = 211 };

    // Each branch's folders, the first time it opens: a query in a real app.
    private ValueTask<IEnumerable<Folder>> LoadFolders(string id, CancellationToken token) =>
        ValueTask.FromResult(Drive.In(int.Parse(id)));

    private void Save() => _saved = Drive.PathOf(Model!.FolderId);

    public sealed class Upload
    {
        [Required(ErrorMessage = "Choose a folder")]
        [Display(Name = "Folder")]
        public int? FolderId { get; set; }
    }

}

Static: Opening a branch fetches its folders from the page, so there's no endpoint to write.

Details

The field shows the chosen item's ItemText. When two items share a name, have ItemText return a path ("West / Sales"). The tree opens on the chosen item, its branch open.

For a large tree, ItemHasChildren and ChildrenProvider load a branch's children the first time it opens, as in TreeView. A chosen value in a branch still to load has no item to name it, so ValueText does:

razor
<TreeSelect ... ItemHasChildren="f => f.HasFolders" ChildrenProvider="LoadFolders"
            ValueText="id => Folders.PathOf(id)" />

How it works three ways:

  • No script: the button opens the panel (the Popover API), whose radio buttons post with the form. The field's text changes once the form posts.
  • With IzzyBlazor's script: the tree takes the arrow keys, choosing closes the panel and the field shows the choice at once; Searchable narrows the tree.
  • Interactive: the same, and @bind-Value follows the choice.

Mode support

What works in each mode, TreeSelect
FeatureStaticInteractive
Choose one item from a tree, posted with the formYesYes
The field shows the choice as it's madeYesYes
One Tab stop, arrow keys and typeahead in the treeYesYes
A search box that narrows the treeYesYes
A clear button (Clearable)YesYes
@bind-Value follows the choiceNoYes

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

Without JavaScript

Every page starts as plain HTML: before IzzyBlazor's script loads on a static page, while an interactive page prerenders, and with JavaScript off. With JavaScript off, the panel opens with radio buttons in branches; the field's text changes once the form posts, the search box needs script, and there's no clear button.

Accessibility

  • The field is a button named by its label and the chosen text ("Category Phones"), with aria-haspopup="dialog", the hint and errors as its description. Without a label, give it an aria-label. The placeholder isn't part of its name.
  • The panel is a non-modal dialog named by the label. With IzzyBlazor's script the tree in it is an ARIA tree (one Tab stop, the arrow keys between items, each treeitem saying whether it's selected, and an item that can't be chosen saying nothing); with JavaScript off it's radio buttons in branches that open.
  • With IzzyBlazor's script, opening it moves focus to the search box with Searchable, else the chosen item, else the first; choosing or Escape closes it and puts focus back on the field, and Tab out of it closes it. With JavaScript off, focus stays on the field.
  • The clear button is named "Clear" (IzzyText.Clear).

Keyboard navigation

TreeSelect keys
Press this keyTo do this
Enter or Space or Down or UpOpen the tree (on the field)
DownMove from the search box to the first match
Up or DownMove to the item above or below
RightOpen an item's branch, or move to its first child (Left on right-to-left pages)
LeftClose an item's branch, or move to its parent (Right on right-to-left pages)
Home or EndMove to the first or last item
*Open every branch beside the focused item
Enter or SpaceChoose the item and close; on one that can't be chosen, open or close its branch
A letterMove to the next item starting with it
EscapeClose without changing the choice
TabClose and move on

Parameters

TreeSelect parameters
PropTypeDefault
ItemValueThe value an item stands for, which is bound and posted, such as its id.Func<TItem, TValue>?Required
ValueTextNames the chosen value when its item isn't in the tree yet: in a branch still to load (ChildrenProvider).Func<TValue, string>?computed
ItemsThe items at the top of the tree.IEnumerable<TItem>?
ItemChildrenAn item's children, or null or empty when it has none.Func<TItem, IEnumerable<TItem>?>?
ItemTextAn item's text in the tree and in the field once chosen.Func<TItem, string?>?computed
ItemDescriptionA muted second line under an item's text in the tree.Func<TItem, string?>?
ItemIconAn icon before an item's text in the tree.Func<TItem, IconData?>?
ItemTemplateMarkup for each item in the tree, in place of its text, description and icon.RenderFragment<TItem>?
ItemExpandedStarts an item's children open.Func<TItem, bool>?
ItemDisabledDims an item and stops it being chosen.Func<TItem, bool>?
ItemSelectableWhether an item can be chosen; one that can't is a label for its branch, and with IzzyBlazor's script a click on it opens or closes the branch.Func<TItem, bool>?
SearchableA search box at the top of the panel that narrows the tree as you type: matches and their parents stay, their branches open.boolfalse
SearchLabelThe search box's name and placeholder.string?computed
ItemHasChildrenSays an item has children to load with ChildrenProvider when its branch first opens, for items whose ItemChildren is empty.Func<TItem, bool>?
ChildrenProviderLoads an item's children, given its key (its value's string form), the first time its branch opens: in the component on interactive pages, and on static pages by the script fetching the page with the key.Func<string, CancellationToken, ValueTask<IEnumerable<TItem>>>?
PlaceholderText in the field while nothing is chosen, such as "Choose a category".string?
EmptyTextShown in the panel when there are no items.string?computed
ClearableA button in the field that empties it, for a value that can be empty, there while one is chosen.boolfalse
ReadOnlyMakes the field read-only: the chosen text shows in a read-only text field, and the value still posts.boolfalse
@bind-ValueThe value, bound with @bind-Value.TValue
DisplayNameThe field's name in validation messages from the input itself, such as a value that can't be parsed.string?

See also

  • MultiTreeSelect: opens a tree from a field to pick several nodes, shown as chips in the space of one input.
  • TreeView: shows items nested in items, such as folders, as branches that open and close.
  • Combobox: lets the user type to filter a list of options, with server search on interactive pages.
  • Select: shows a native select, themed where the browser allows.

Connection lost

Rejoining the server…