Ant Design Svelte

TreeSelect

Selecting tree nodes with search, loading and associated marks.

When to use

TreeSelect selects a department, documentation section, or other entry from a hierarchy. The tree is expanded in one pane, and the value contains the node key. If your application needs the full path and separate level columns, use Cascader.

Pass nested treeData with unique values. The title explains the choice to the person; key can be set separately, but the value of the model is determined by value. For a permanent tree without an input field, Tree is intended.

TreeSelect CSS Prefixes show global ConfigProvider.prefixCls and local prefixCls without resetting state. Control and tags use Select prefix; popup adds the suffix -tree-dropdown. The nested tree preserves the native Tree adapter and its own classes: the local prefix TreeSelect is not equal to Tree.prefixCls.

Data schemas and declarations

Custom schema and flat data maps value/label/children through fieldNames and demonstrates treeDataSimpleMode. Search defaults to the literal value field, so set showSearch.treeNodeFilterProp explicitly for another schema. Selection and filter callbacks receive the original custom fields. Simple mode builds standard children from id/pId; keep the children field name unchanged when combining it with fieldNames. Input data is not mutated.

Declarative nodes use TreeSelect.TreeNode and the named TreeSelectTreeNode. treeData takes precedence over declarations. Strategies are available as TreeSelect.SHOW_PARENT, SHOW_CHILD and SHOW_ALL. Icon and switcherIcon accept content or a snippet with TreeEventNode. class/style, data-* and aria-* apply to the row; styles.popup.item overrides its own style.

Node value

Single returns a string or numeric key. multiple returns an array of keys. With labelInValue, an object with value and label is used instead of a key; treeCheckStrictly enables this format automatically.

Problem Setting Example
Select one node treeData, value, onChange Selecting a node from treeData
Select independent nodes multiple Multiple nodes
Tag a branch with descendants treeCheckable Related marks
Check the checkbox regardless treeCheckStrictly Independent marks
Receive a key along with a signature labelInValue Value with signature

The managed control receives value and reports a new choice via onChange. Unlike components with bind:value, here the application itself assigns the result to its state. defaultValue specifies the initial local value. Clearing single reports undefined, multiple reports an empty array; the basic example normalizes no selection to null.

The second argument to onChange contains signatures or null in the format labelInValue, the third - triggerValue. This is the key of the node that caused the change, not its parent path. For the path, build a map of the parents using treeData in advance.

Related marks

treeCheckable enables multiple and parent-child relationships. SHOW_CHILD returns the leaf marked nodes, SHOW_PARENT merges the entire branch, SHOW_ALL includes the parent and children. Comparison of strategies shows the difference in results; The strategy affects the model produced, not just the signature.

treeCheckable accepts TreeSelectCheckableContent: boolean, text, numbers, bigint, snippets, nested arrays, iterables and Promise objects. Only JavaScript truthiness is used. false, null, undefined, "", 0, -0, NaN and 0n do not enable checkboxes; [], snippets and Promise objects enable standard checkboxes. The content is not rendered: snippets are not invoked, iterables are not iterated and Promise objects are not awaited.

treeCheckable content compares these flags. The example explicitly enables multiple, so the selected-value array is retained when checkboxes are turned off.

treeCheckStrictly disables the mark association and returns objects with value and label. When changing modes, match the state type to the new format. For regular multiple without checkbox, nodes are selected independently.

selectable=false disables header selection, preserving branch expansion. disabled blocks the node, disableCheckbox specifically disables the checkbox, checkable=false removes its checkbox. The basic example allows you to expand Interface without selecting that heading.

Selection limit

TreeSelect selection limit demonstrates maxCount for multiple, linked checkboxes and treeCheckStrictly. Initial and controlled values are not trimmed when the limit decreases; missing values also count. Selected nodes can still be deselected, and the selection can be cleared after reaching the limit. This limits selection, not the number of visible tags: maxTagCount limits visible tags.

Explicit showCheckedStrategy=SHOW_PARENT disables a nonzero limit. SHOW_ALL disables it without treeCheckStrictly; for plain multiple, do not set this strategy explicitly if you need a limit. SHOW_CHILD and strict mode retain the limit. maxCount=0 prevents new values even with SHOW_PARENT/SHOW_ALL; the limit does not apply to single selection.

With SHOW_CHILD, a parent branch can become unavailable if its direct enabled children exceed the remaining capacity. The final number of values after linked checking is also checked. An attempted selection can call onSelect/onDeselect without onChange if the resulting set exceeds a nonzero limit. Changing maxCount preserves the current selection; switching modes in the example explicitly clears it to align the key and strict object formats.

Title expansion

TreeSelect title expansion demonstrates treeExpandAction=false, click and doubleClick. By default, clicking a title only selects the node. treeExpandedKeys and onTreeExpand control expansion independently of value; changing the mode preserves state.

In click mode, onTreeExpand runs before onChange/onSelect. In multiple mode, a real double click performs two ordinary selection actions before expanding the branch. Ctrl/Meta/Shift suppress title expansion while preserving selection. The switcher, checkbox and keyboard work independently; Enter selects the active node. Explicit isLeaf=true prevents expansion; disabled prevents selection but allows title expansion.

Focus and events

TreeSelect focus and events demonstrates showAction=['focus'] and an event log. The popup opens before onFocus. An empty array or ['click'] retains ordinary pointer opening. Changing showAction while the input is already focused does not open the popup on its own. autoFocus and tabIndex set input attributes; native autofocus and tabindex take precedence. During hydration, autofocus preserves focus on another control. As in the original, maxLength does not limit search; native maxlength sets the browser input limit.

Native input onkeydown runs first, followed by onInputKeyDown, internal handling and root onKeyDown. Use event.preventDefault() in native onkeydown to cancel selection or opening. preventDefault in onInputKeyDown does not cancel selection; stopPropagation stops the root callback. Holding Enter selects once until keyup or blur. Space opens a readonly control; Escape closes it. Enter/Space on the clear button does not reach root onKeyDown.

onFocus/onBlur receive actual focusin/focusout events. Root callbacks receive the actual root as currentTarget, a DIV by default; native editor handlers receive an input or textarea. The popup has its own DOM event boundary. Keyboard and outside-pointer closing is deferred until after the root key/blur callback. Server rendering does not run callbacks, autofocus or timers.

The events example lets you switch single/multiple mode and search. Clicking an open single-select control again closes it when search is disabled and keeps it open when search is enabled. In multiple mode, clicking the input keeps the popup open; clicking the field's free area toggles it. Clearing a single-select control with the mouse closes the popup asynchronously; in multiple mode it retains its state. The control's onFocus/onBlur and onClick do not receive popup events, including events from custom content.

Tags and returned labels

Tag display compares numeric and responsive maxTagCount. It limits visible tags; full values remain in callbacks and FormData. maxTagTextLength truncates only string and number labels while preserving the full tooltip text and labels. Snippets and arrays remain opaque content. Responsive tags are measured after mount; server-rendered tags stay hidden until measurement.

tagRender receives TreeSelectTagInfo: render label as a snippet and use closable/onClose for removal. The summary has isMaxTag=true and no value/index/onClose. maxTagPlaceholder receives complete omitted records. With treeTitleRender, the onChange label becomes a bound snippet: it is in labels in raw mode and in the value record with labelInValue/strict, where labels is null. Custom node title saves a snippet and renders it after the control unmounts. Check typeof label === 'function' before rendering; JSON.stringify does not display snippet content.

Control, popup and styling

Control and popup slots demonstrates prefix, suffix and popupRender. suffix receives open, focused, searchValue, showSearch and loading; it takes precedence over suffixIcon, while null/undefined restore icon selection. suffixIcon=null hides the arrow. removeIcon changes the ordinary tag removal icon. allowClear accepts an object with clearIcon and the accessible label. Clearing a nonempty search calls onSearch with an empty string.

FormItem.hasFeedback adds a validation icon beside the default arrow. suffixIcon=null hides the arrow but keeps feedback. A custom suffix replaces this area's content and does not add feedback automatically.

In popupRender, render the supplied menu snippet to retain the original tree. An embedded field can receive focus and retain its draft between popup openings. Semantic styles demonstrates classNames/styles objects and functions. Control slots include root, prefix, input, suffix, clear, content, placeholder, item, itemContent and itemRemove; popup contains root, item, itemTitle and itemSwitcher. Functions receive resolved props. Styles are CSS strings. ConfigProvider.treeSelect sets variant, classNames, styles and switcherIcon; local classes merge with provider classes, while a local popup slot string replaces the matching provider style. A nested provider record replaces the entire parent record.

onPopupVisibleChange, popupStyle, choiceTransitionName and local direction are accepted but have no effect. Use onOpenChange for events, styles.popup.root for styling and ConfigProvider.direction for RTL. Semantic callbacks receive the original values. Native HTML dir remains a separate attribute.

Popup alignment

TreeSelect popup alignment compares popupAlign with builtinPlacements. The former overrides fields of the selected placement; offset, targetOffset and overflow are replaced as whole values. Percentages in offset refer to the popup, while percentages in targetOffset refer to the control.

builtinPlacements replaces the entire map of four placements, including an explicitly empty object. A missing placement uses centering rather than the default entry from the previous map.

ConfigProvider.popupOverflow selects the default map region: the viewport or the scroll document region. The shared example demonstrates inheritance and an explicit viewport. A custom builtinPlacements, including an empty map, replaces the default map; local popupAlign.htmlRegion takes precedence. Changing the shared mode updates the map for the next alignment, retaining the current coordinates.

An open popup retains its calculated alignment until placement changes, the control or popup resizes, the window emits resize or an ancestor scrolls. Replacing the map alone does not recalculate coordinates. Changing popupAlign triggers an immediate recalculation only when the selected entry is absent from the map.

Popup animation

TreeSelect popup animation demonstrates the default transition, a custom CSS name, animation and disabling named motion. transitionName=undefined selects the default slide-up with the ConfigProvider prefix; transitionName="" disables named motion. A nonempty animation takes precedence and forms a name from the Select prefix, -dropdown- and its value.

Provide enter and leave CSS for a custom name; the example uses a fade. Completing the CSS effect completes its phase. A name without CSS receives no artificial completion timer. The popup retains its DOM after leaving, reopening interrupts closing, and multiple search is retained. These options affect the popup rather than tree branch expansion.

theme.token.motion=false disables starting named motion when opening. Changing the setting or name during an active phase does not forcibly complete it.

Custom components

components.root replaces the entire control: default tags, affixes and components.input are not rendered. In the root example, Button displays the selected label and receives ARIA attributes for opening the tree. Removing the root slot restores the default selector with the current value.

components.input replaces only the editor, retaining selector styling, tags and the suffix. The textarea editor demonstrates editor replacement, responsive tags and callback order. Search and selection remain separate data.

With multiple and maxTagCount="responsive", the custom editor participates in tag measurement and its suffix can become absolutely positioned. Resizing the control or editor updates the number of visible tags. The popup retains its anchor during resize and scroll events, including in RTL.

The snippet receives attributes and register. Apply attributes to the actual DOM element and register it with {@attach register}. For a library component, you can register an object with inputElement, nativeElement and focus/blur methods. Use the returned cleanup in $effect; refs are released on replacement or unmount. The Form example forwards attributes to Input, retains TreeSelect as the associated field and does not submit the search as a second form value.

An object of the form { render, props } adds custom attributes. For input, these take priority and custom callbacks run before internal handlers; for root, generated attributes take priority and internal callbacks run first. Apply the merged attributes to retain handlers. Use TreeSelect's native onkeydown to cancel keyboard processing.

The RootElement and EditorElement parameters refine event and ref types. bind:nativeElement returns the current root; bind:inputElement returns an input or textarea, and is absent with a root slot. Removing a slot restores the default div/input. A custom root owns value rendering, ARIA and native restrictions, including disabled.

Virtualization and scrolling

popupMatchSelectWidth matches the control width for true, fits the content for false, or sets a numeric width in px. The control width remains the minimum. An omitted prop or undefined inherits ConfigProvider.popupMatchSelectWidth. Shared popup width compares inheritance with a nested true and a local number on Select.

Large tree contains 600 nodes. virtual inherits ConfigProvider.virtual and defaults to true. listHeight limits the viewport, listItemHeight provides the initial row height estimate, and listItemScrollOffset adds an offset when moving to the active node. popupMatchSelectWidth=false disables virtualization; a numeric value sets popup width. The property inherits ConfigProvider when not set locally.

bind:this exposes TreeSelectRef with focus, blur and scrollTo. The method accepts coordinates or key/index with align and offset. For a branch target, autoExpand expands its internal path if expansion is not specified in props. onPopupScroll receives the tree viewport event. Arrows and Enter continue to operate on the active node; aria-activedescendant points to the row while it is in the DOM.

showScrollBar is accepted as an inherited property, but is not forwarded to the tree and does not affect scrolling. Do not use it to control the TreeSelect scrollbar.

Display and form

treeTitleRender and switcherIcon accept Svelte snippets. Your signatures change the display of a node without changing its value. popupMatchSelectWidth sets the width of the panel, listHeight — the height; for long signatures, check the panel on a narrow screen.

TreeSelect supports virtualization, field schemas, simple mode, tags, popup slots and semantic styles. The supported properties are listed in API.

In subscription form, onChange updates form.setFieldValue and reset restores initialValues. label specifies the available field name. Arrows move focus through the tree, Enter selects a node, Escape closes the popup; focus/blur are accessible through the component instance.

TreeSelect uses design tokens from the current theme for its appearance.

Examples

null

Selecting a node from treeData

The tree is specified via treeData. Single returns the key of the selected node; parent The interface is expanded but not selected.

["button"]

Multiple nodes

multiple selects nodes independently. The selected labels form tags; removing the tag changes the model.

[]

Related marks

treeCheckable enables multiple and parent-child relationships. By default, SHOW_CHILD returns leaf nodes.

[]

treeCheckable content

Text, an empty array and a snippet enable standard checkboxes. Their content is not rendered; multiple retains the selected-value array.

["button"]

Changing the limit preserves selection; changing the mode clears it in this example. SHOW_PARENT and non-strict SHOW_ALL disable a nonzero limit; maxCount=0 prevents new selections.

TreeSelect selection limit

maxCount limits multiple and checkbox selection. Compare strategies and strict mode; initial values exceeding the limit are preserved.

SHOW_ALL

SHOW_PARENT

SHOW_CHILD

Strategies for marked nodes

SHOW_ALL shows the parent and children, SHOW_PARENT collapses the branch, SHOW_CHILD leaves the leaves.

[]

Independent marks

treeCheckStrictly disables parent-child relationships and enables labelInValue. The result is objects with value and label.

null

Value with label

labelInValue returns an object instead of a simple key. A numeric key retains the type number.

Catalog ready

Asynchronous download

loadData returns a Promise and updates treeData. The search does not bring up the bootloader. The timer and pending Promise terminate when unmounted.

[]

[]

Ctrl, Meta and Shift preserve selection without expanding by title. The switcher button and keyboard work independently.

TreeSelect title expansion

treeExpandAction: false, click or doubleClick. Selection and expansion are controlled independently; changing the mode preserves state.

Tree lines and switch

treeLine shows connections, showLeafIcon controls leaves. switcherIcon gets TreeEventNode; treeIcon includes node icons.

Tree position

Four placement values ​​specify the preferred placement of the popup. classNames.popup.root adds the panel frame class.

popupAlign.offset: [16, 12]

builtinPlacements: 16 px popup gap

TreeSelect popup alignment

PopupAlign changes the offset; builtinPlacements replaces the placement map. Compare the gaps for the two controls.

TreeSelect popup animation

The default transition, a custom CSS name and animation. An empty transitionName disables named motion; animation takes precedence.

Design options

outlined, filled, borderless and underlined use the same tree and node selection.

Test states

error and warning specify the status. A completely inaccessible field and an inaccessible node are shown separately.

Dimensions

large, medium and small. A field without a local size inherits the section settings.

Own node label

treeTitleRender - Svelte snippet. It changes the label in the tree and the selected value, preserving the key.

fieldNames

treeDataSimpleMode

Custom schema and flat data

fieldNames maps record fields; treeDataSimpleMode builds an id/pId hierarchy. The callback receives the original fields.

["button","input","table","select"]

TreeSelect tag display

Numeric and responsive limits affect visible tags; tagRender and maxTagPlaceholder receive complete labels.

TreeSelect control and popup slots

prefix, suffix, a clear icon and popupRender. The popup field retains its draft when reopened.

Semantic styles TreeSelect

ConfigProvider defaults, a styles function, placeholder and switcher snippets. A local slot overrides provider styles.

Large TreeSelect tree

600 nodes, ConfigProvider.virtual, row height estimates and scrolling to a key through TreeSelectRef.

Declarative TreeSelect nodes

TreeSelect.TreeNode and named TreeSelectTreeNode, a static strategy, icons and row styling.

[]

TreeSelect focus and events

showAction opens the tree on focus. The log shows native, input and root callback order and Enter cancellation.

Selected: null

nativeElement: —

Custom TreeSelect root

components.root replaces the entire control. Button receives attributes and registers its DOM; the owner supplies its label and ARIA.

Selected: ["button","input"]

inputElement: —

Custom TreeSelect editor

components.input replaces only the editor. Textarea retains tags and responsive layout; the log shows props, native, hook and root callbacks.

—

Custom editor in Form

Input registers a composite ref with focus/blur. Form stores the selected node, validates the field and remounts the editor on reset.

Subscription to sections in Form

Original form from the review: associated check-ins, search, required selection, submit and reset. Form stores leaf keys.

["docs"]
General: suite; local: project-tree-select

Without a local value, control uses the general -select, popup uses the general -tree-select-dropdown. With local prefixCls both use the same namespace and popup adds -dropdown. The nested tree preserves the native Tree adapter and its own classes: the local prefix TreeSelect is not equal to Tree.prefixCls.

CSS prefixes TreeSelect

Common namespace ConfigProvider and local prefixCls; the state of the component is preserved when the name is changed.

API

Core TreeSelect topics and additional public APIs. Basic and Generate from tree data are combined; separate examples demonstrate popup alignment and animation.

Topic coverage TreeSelect
ThemeExample or limitation
Basic / Generate from tree dataA treeData hierarchy; declarative nodes are demonstrated separately.
Multiple SelectionIndependent selection and removal of tags.
CheckableRelated checkbox; additional strategies and strict are shown separately.
treeCheckable contentThe flag enables checkboxes without rendering its content.
Asynchronous loadingPromise, tree update and cleanup.
Show Tree LineLines, leaves and switcher snippet.
TreeSelect title expansionThree treeExpandAction modes and controlled treeExpandedKeys.
PlacementFour panel positions.
TreeSelect popup alignmentOffset and a custom placement map.
TreeSelect popup animationDefault and custom transitions, and disabling animation.
VariantsFour field designs.
StatusError, warning and disabled.
Max CountmaxCount limits selection; maxTagCount limits visible tags only.
Prefix and Suffixprefix, suffix, suffixIcon, removeIcon and popupRender.
Custom semantic dom stylingclassNames/styles objects and functions; ConfigProvider.treeSelect defaults.
TreeSelect focus and eventsOpening on focus, callback order and cancelling keyboard handling.
Search separatorsSeparator array, function, pasted lines and retaining selected values.
Custom TreeSelect rootFull control replacement, attributes, DOM registration and restoring the default root.
Custom TreeSelect editorTextarea instead of input, retaining tags and handler order.
Custom editor in FormInput composite ref, field focus, validation and reset.
Virtual listVirtual rows and scrollTo by key.
TreeNodeDeclarations, icons and row attributes.
TagsTruncation and responsive tag layout.
Data schemasCustom fields and a flat list.
Basic parameters TreeSelect
PropertyDescriptionTypeDefault
componentsRoot replaces the entire selector and takes priority over input. Input replaces the editor, retaining tags and affixes. A snippet receives attributes/register; an object also accepts props.TreeSelectComponents<RootElement, EditorElement>undefined
tokenSeparatorsA readonly string array or (text: string) => string[]. Splitting clears search and closes the popup without onChange/onSelect; IME waits for compositionend.TreeSelectTokenSeparatorsundefined
showScrollBarAccepted for compatibility, but not forwarded to the tree and does not affect scrolling.boolean | "optional"undefined
showActionFocus adds opening on focus. An empty array and click retain pointer opening; changing props while already focused does not open the popup.('focus' | 'click')[]undefined
autoFocusInput autofocus after mount; native autofocus takes precedence. Hydration preserves focus on another control.booleanundefined
tabIndexInput keyboard focus order; native tabindex takes precedence.numberundefined
maxLengthAs in the original, does not limit TreeSelect search. Use native maxlength for a DOM input limit.numberundefined
onInputKeyDownInput hook after native onkeydown. Its preventDefault does not cancel selection; use native onkeydown to cancel it.DOMAttributes<EditorElement | HTMLInputElement>['onkeydown']undefined
onKeyDownRoot keyboard callback after internal handling. onKeyUp reports key release.DOMAttributes<RootElement | HTMLDivElement>['onkeydown']undefined
onFocusActual focusin; onBlur receives focusout. currentTarget is the DOM root, a DIV by default.DOMAttributes<RootElement | HTMLDivElement>['onfocusin']undefined
onMouseDownRoot control event; onClick, onMouseEnter and onMouseLeave are also supported.DOMAttributes<RootElement | HTMLDivElement>['onmousedown']undefined
stylesSemantic slot CSS strings; local popup slots replace matching provider styles.TreeSelectSemanticValue<TreeSelectStyles>undefined
childrenTreeSelect.TreeNode or TreeSelectTreeNode; treeData takes precedence over declarations.Snippetundefined
fieldNamesField names for value, label and children. Set treeNodeFilterProp explicitly to search a custom label field.TreeSelectFieldNamesvalue / label / children
treeDataSimpleModeBuilds children from id/pId; rootPId specifies the root parent. The children field name remains standard.boolean | TreeSelectSimpleModeConfigfalse
maxTagCountNumber of visible tags. All selected values remain in callbacks and FormData.number | "responsive"undefined
maxTagTextLengthTruncates tag text; tooltip and callbacks retain full labels.numberundefined
maxTagPlaceholderSummary content or a snippet with omitted records and complete labels.TreeSelectTagPlaceholder+ N ...
tagRenderlabel is a snippet; closable/onClose manage removal. The summary has isMaxTag=true and no value/index/onClose.Snippet<[TreeSelectTagInfo]>undefined
popupRenderCustom popup; calling menu() retains the original tree. Embedded fields can receive focus.Snippet<[Snippet]>undefined
prefixContent before the input.TreeSelectLabelundefined
suffixContent or a snippet with open, focused, searchValue, showSearch and loading; takes precedence over suffixIcon.TreeSelectSuffixundefined
suffixIconCustom icon; null hides the arrow.TreeSelectLabelStandard pointer
removeIconOrdinary tag removal icon. tagRender provides its own markup.TreeSelectLabel×
placeholderText, number, array or a snippet for an empty control.TreeSelectLabelundefined
virtualRow virtualization. popupMatchSelectWidth=false disables it.booleanConfigProvider.virtual / true
listItemHeightInitial row height estimate; 0 disables virtualization.numbercontrolHeightSM + paddingXXS
listItemScrollOffsetAdditional offset when moving to the active node.number0
popupMatchSelectWidthtrue matches the control width; false fits the content and disables virtualization. A number sets the width in px; the control width remains the minimum. undefined inherits ConfigProvider.boolean | numberConfigProvider / true
treeIconEnables node icons from the icon field. A function acts as a flag; node data supplies the content.TreeSelectNodeIconfalse
switcherIconContent or a snippet with TreeEventNode. A local value overrides the provider; false leaves an empty switcher.TreeSelectSwitcherIconConfigProvider.treeSelect
prefixClsFull local prefix of Select control and TreeSelect popup. Without it, the generic -select and -tree-select are used; with it both get one namespace. Native Tree adapter saves native classes.stringConfigProvider.prefixCls + "-select"
classNamesControl, tag and popup classes; an object or a function receiving info.props.TreeSelectSemanticValue<TreeSelectClassNames>undefined
treeDataHierarchy with unique value. Supports custom fields, icon, switcherIcon, class/style and row data-* and aria-* attributes.readonly Data[][]
valueManaged key, signed object, or array. When clearing single, accept undefined as null to preserve managed mode. bind:value is not supported.TreeSelectValueundefined
defaultValueInitial local value, read once.TreeSelectValueundefined
onChangeNew value and extra.triggerValue. treeTitleRender returns label snippets; with labelInValue they are in value and labels is null.(value, labels, extra) => void—
multipleIndependent selection of multiple nodes. treeCheckable and treeCheckStrictly also include multiple.booleanfalse
treeCheckableThe value is a flag: a truthy value enables standard checkboxes and multiple. Empty arrays and snippets enable checkboxes; their content is not rendered.TreeSelectCheckableContentfalse
maxCountmultiple selection limit, including checkbox/strict and missing values. Does not trim initial values. Explicit SHOW_PARENT and non-strict SHOW_ALL disable a nonzero limit; 0 prevents new selections. Does not apply to single selection.numberundefined
treeCheckStrictlyIndependent checkbox and automatic labelInValue.booleanfalse
showCheckedStrategyManages the tags and result of the associated selection. Without treeCheckable, SHOW_ALL is used.SHOW_ALL | SHOW_PARENT | SHOW_CHILDSHOW_CHILD with treeCheckable
labelInValueObjects { value, label, halfChecked? } instead of simple keys.booleanfalse
showSearchThe object contains searchValue, onSearch, filterTreeNode, treeNodeFilterProp and autoClearSearchValue. To search by label, specify title.boolean | TreeSelectSearchConfigsingle: false; multiple: true
loadDataLoads children with treeData updated. Not called during search.(node) => PromiseLike<unknown>—
treeExpandedKeysControlled expansion with onTreeExpand; treeDefaultExpandedKeys and treeDefaultExpandAll set the start.readonly TreeKey[]Local state
treeExpandActionTitle expansion. Ctrl/Meta/Shift suppress expansion while preserving selection. In click mode, onTreeExpand precedes onChange/onSelect.false | "click" | "doubleClick"false
treeLoadedKeysManaged loaded nodes with onTreeLoad.readonly TreeKey[]Local state
treeLineTree connections and display of leaves. treeIcon includes node icons.boolean | { showLeafIcon: TreeSelectSwitcherIcon }false
treeTitleRenderNode content and returned labels. A snippet can be saved and rendered after the control unmounts.Snippet<[Data]>Node label
allowClearClearing and onClear. An object sets clearIcon and the accessible label; a nonempty search is cleared with onSearch.boolean | TreeSelectAllowClearfalse
openControlled popup with onOpenChange, defaultOpen sets the start.booleanLocal state
listHeightTree viewport height. onPopupScroll receives the event from this container.number256
placementPreferred popup side. popupMatchSelectWidth sets the width, getPopupContainer sets the container.topLeft | topRight | bottomLeft | bottomRightIn interface direction
popupAlignOverrides fields of the selected placement; offset, targetOffset and overflow are replaced as whole values. Coordinates are retained until an alignment trigger.TreeSelectPopupAlignundefined
builtinPlacementsReplaces the entire placement map. An empty object does not restore defaults; a missing placement centers the popup.Readonly<Record<string, TreeSelectPopupAlign>>undefined
animationA nonempty value selects a transition from the Select prefix and animation suffix, overriding transitionName. A custom name requires CSS.stringundefined
transitionNameThe popup CSS transition name. undefined selects the default slide-up; an empty string disables named motion.stringConfigProvider.prefixCls + "-slide-up"
onOpenChangeReports a request to open or close the popup. In controlled mode, update open with this value.(open: boolean) => voidundefined
onPopupVisibleChangeAccepted without being invoked. Use onOpenChange for popup state changes.(open: boolean) => voidundefined
popupStyleAccepted without being applied. Set popup styling through styles.popup.root.stringundefined
choiceTransitionNameAccepted, but the current Overflow does not apply tag animations.stringundefined
directionAccepted without changing direction. ConfigProvider controls RTL and the default placement; HTML dir is a separate attribute.ltr | rtlConfigProvider.direction
sizeField size; status — error or warning.large | medium | smallFrom ConfigProvider
variantLocal prop → closest Form.variant → ConfigProvider.treeSelect.variant → shared ConfigProvider.variant → outlined.VariantFrom context / outlined
nativeElementRef of the registered root. Without components.root it returns a div; cleared on unmount.RootElement | HTMLDivElement—
inputElementEditor ref: input or textarea. There is no editor with components.root; removing the input slot restores the default input.EditorElement | HTMLInputElement—

Full types are included in the package. ConfigProvider.treeSelect sets variant, classNames, styles and switcherIcon. Local classes merge with provider classes; local popup slot CSS strings replace the matching provider styles.

Methods

bind:this exposes TreeSelectRef with focus(options?), blur() and scrollTo(config). bind:inputElement and bind:nativeElement expose the DOM elements.

<script lang="ts">
  import { Button, TreeSelect, type TreeSelectRef } from '@woodger/antd';

  let control = $state<TreeSelectRef>();
</script>

<style>
  .controls {
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 12px;
  }
</style>

<div class="controls">
  <TreeSelect
    bind:this={control}
    aria-label={("TreeSelect Methods")}
    style="width:min(100%,240px)"
    treeData={[{ value: 'docs', title: "Documentation" }]}
  />
  <Button onclick={() => control?.focus()}>{("Focus TreeSelect")}</Button>
  <Button onclick={() => control?.blur()}>{("Remove focus TreeSelect")}</Button>
</div>

DOM and accessibility

The default editor has role combobox, aria-haspopup="tree", aria-expanded, aria-controls and an active descendant. components.input receives these in attributes; the owner handles accessibility for components.root. The popup contains treeitems and checkboxes; aria-label or FormItem supplies the accessible name.

Arrows move the active node and expand branches, Enter selects, Escape closes the popup. The search preserves the visibility of the parents of the matched nodes. Unavailable branches and selectable=false limit the corresponding actions.

The panel class is specified via classNames.popup.root; position example shows its outline. classNames and styles support control, tag and popup slots, including functions receiving info.props. treeTitleRender, icon and switcherIcon provide node content. Use the tokens below to style the tree.

Registration tokens

All seven component tokens are checked against ant.design and applied via theme.components.TreeSelect. The outer field also uses Select component tokens. The nested provider isolates the design from neighboring examples.

<script lang="ts">
  import { ConfigProvider, TreeSelect } from '@woodger/antd';
</script>

<ConfigProvider theme={{
  components: {
    TreeSelect: {
      titleHeight: 36,
      switcherSize: 24,
      indentSize: 28,
      nodeHoverBg: '#f9f0ff',
      nodeHoverColor: '#531dab',
      nodeSelectedBg: '#722ed1',
      nodeSelectedColor: '#fff'
    }
  }
}}>
  <TreeSelect
    aria-label={("TreeSelect Tokens")}
    treeDefaultExpandAll
    defaultValue="button"
    style="width:min(100%,320px)"
    treeData={[
      {
        value: 'ui', title: "Interface", children: [
          { value: 'button', title: 'Button' }, { value: 'input', title: 'Input' }
        ]
      }
    ]}
  />
</ConfigProvider>
TreeSelect Component Tokens
TokenPurpose
indentSizeTree level indentation.
switcherSizeWidth of the branch switch area.
titleHeightThe node's row height.
nodeHoverBgNode background when hovered.
nodeHoverColorNode hover color.
nodeSelectedBgBackground of the selected node.
nodeSelectedColorColor of the selected node.

Common tokens of the current topic

Values ​​are read through theme.useToken() and react to section settings.

Common TreeSelect Tokens
TokenCurrent value
colorBgContainer#ffffff
colorBgContainerDisabledrgba(0,0,0,0.04)
colorBgElevated#ffffff
colorBgTextHoverrgba(0,0,0,0.06)
colorBorder#d9d9d9
colorFillQuaternaryrgba(0,0,0,0.02)
colorPrimary#2f54eb
colorPrimaryBorder#adc6ff
colorPrimaryHover#597ef7
colorSplitrgba(5,5,5,0.06)
colorTextrgba(0,0,0,0.88)
colorTextDisabledrgba(0,0,0,0.25)
colorTextQuaternaryrgba(0,0,0,0.25)
colorWhite#fff
borderRadius6
borderRadiusSM4
controlInteractiveSize16
controlItemBgActiveDisabledrgba(0,0,0,0.15)
controlItemBgHoverrgba(0,0,0,0.04)
fontFamily-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, 'Noto Sans', sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'
fontSize14
fontSizeLG16
fontWeightStrong600
lineHeight1.5714285714285714
lineTypesolid
lineWidth1
lineWidthBold2
lineWidthFocus3
marginXS8
motiontrue
motionDurationFast0.1s
motionDurationMid0.2s
motionDurationSlow0.3s
motionEaseInBackcubic-bezier(0.71, -0.46, 0.88, 0.6)
motionEaseOutBackcubic-bezier(0.12, 0.4, 0.29, 1.46)
paddingXS8

FAQ

How to get the parent in onChange?

Map the selected value or extra.triggerValue to the original treeData or parent map. The full path is not added to extra.

Why doesn't the search call loadData?

Search filters a known tree. Expand the lazy branch outside of search, or organize a server-side search via showSearch.onSearch and updating treeData.

Why are several nodes selected at once?

treeCheckable links parent to children and enables multiple. treeCheckStrictly disables this relationship and enables labelInValue; regular multiple selects nodes without associated marks.

How to show long signatures?

Set popupMatchSelectWidth to a number or false and check the accessibility of the panel on a narrow screen. listHeight changes the viewport height; virtual controls virtualization.