Vue DropDownBox - Search in Embedded Components

When using DevExtreme DropDownBox with an embedded DataGrid or TreeList component, you may want to allow users to search and filter records in the dropdown. DataGrid and TreeList include a built-in search and filter UI that you can activate. You can also make the DropDownBox input field editable, so that it acts as a search box for the embedded control. In this case, you need to implement custom code, because DropDownBox does not have built-in search functionality. The implementation depends on whether a lookup field is involved in the search.

When to Use Each Approach

Implementation AspectSearch by field values (no lookup column involved)Search by display values (lookup column involved)
Embedded componentDataGrid / TreeListDataGrid / TreeList
User inputText that matches values in the main dataset (same record).Text that matches values in the main dataset, a related dataset (lookup display text), or both.
Main API used for searchDataSource.searchValue(value)DataSource.filter(filterExpr)
Extra data source requiredNoYes, a lookup data source
Filtering logicThe DataSource searches for values in fields specified in searchExprYou query the lookup data source by display field (for example, Name contains text), map results to keys, then build an OR filter such as [EmployeeID, '=', 1] or [EmployeeID, '=', 5]
Reset search on closedataSource.searchValue('')dataSource.filter(null)
NOTE
These implementation strategies support single selection only. To implement multiple selection, use the TagBox component instead.

For complete working examples, see the following GitHub repositories:

See Also

Search by Field Values (DataGrid)

This topic covers search by field values (no lookup column involved) in a DropDownBox with an embedded DataGrid. The approach uses DataSource.searchExpr and DataSource.searchValue to filter rows as the user types.

NOTE
For a similar example that involves a lookup column, see Search by Lookup Column (TreeList).

The full working code is available in the GitHub repository:

View on GitHub

1) Configure DropDownBox to Accept User Input

  • Activate acceptCustomValue so the user can type text.
  • Set valueChangeEvent to an empty string to prevent the component from trying to interpret typing as a value change.
DropDownBoxWithDataGrid.vue
  • <DxDropDownBox
  • :accept-custom-value="true"
  • value-change-event=""
  • :open-on-field-click="false"
  • ...
  • />

Use the following DataSource members:

DropDownBoxWithDataGrid.vue
  • import AspNetData from 'devextreme-aspnet-data-nojquery';
  • import { DataSource } from 'devextreme-vue/common/data';
  •  
  • const dataSource = new DataSource({
  • store: AspNetData.createStore({
  • key: 'OrderNumber',
  • loadUrl: `${url}/Orders`,
  • }),
  • searchExpr: 'Employee',
  • });

3) Configure displayExpr

Use displayExpr to define how a selected record is displayed in the input:

Code
  • function displayExpr(item) {
  • if (!item || typeof item !== 'object') return '';
  • return `${item.Employee}: ${item.StoreState} - ${item.StoreCity} <${item.OrderNumber}>`;
  • }

4) Configure the Embedded DataGrid in contentTemplate

Configure the DropDownBox component. Use contentTemplate to embed a DataGrid.

To activate focused row and single row selection, specify the following settings:

DropDownBoxWithDataGrid.vue
  • <template #default>
  • <DxDataGrid
  • ref="dataGridRef"
  • :data-source="dataSource"
  • height="100%"
  • width="100%"
  • :focused-row-enabled="true"
  • v-model:focused-row-key="focusedRowKey"
  • :selected-row-keys="selectedRowKeys"
  • :auto-navigate-to-focused-row="false"
  • :remote-operations="true"
  • :column-auto-width="true"
  • @key-down="dataGridKeyDown"
  • @content-ready="dataGridContentReady"
  • @selection-changed="onSelectionChanged"
  • >
  • <DxColumn data-field="OrderNumber" caption="ID" data-type="number" />
  • <DxColumn data-field="OrderDate" data-type="date" />
  • <DxColumn data-field="StoreState" data-type="string" />
  • <DxColumn data-field="StoreCity" data-type="string" />
  • <DxColumn data-field="Employee" data-type="string" />
  • <DxColumn data-field="SaleAmount" data-type="number">
  • <DxFormat type="currency" :precision="2" />
  • </DxColumn>
  • <DxPaging :enabled="true" :page-size="10" />
  • <DxSelection mode="single" />
  • <DxScrolling mode="virtual" />
  • </DxDataGrid>
  • </template>

5) Implement Search in onInput

Handle the DropDownBox onInput event:

  1. Ensure the dropdown is open
  2. Apply dataSource.searchValue(text)
  3. Load results and move focus to the first match
DropDownBoxWithDataGrid.vue
  • function onInput(e: DxDropDownBoxTypes.InputEvent): void {
  • if (searchTimer.value) clearTimeout(searchTimer.value);
  • searchTimer.value = setTimeout(() => {
  • if (!gridBoxOpened.value) gridBoxOpened.value = true;
  • const text = e.component.option('text');
  • props.dataSource.searchValue(text ?? null);
  • if (isSearchIncomplete(e.component)) {
  • const onChanged = (): void => {
  • const items = props.dataSource.items();
  • if (items.length > 0) {
  • focusedRowKey.value = (items[0] as OrderItem).OrderNumber;
  • }
  • dropDownBoxRef.value?.instance?.focus();
  • props.dataSource.off('changed', onChanged);
  • };
  • props.dataSource.on('changed', onChanged);
  • props.dataSource.load().catch(() => {});
  • }
  • }, props.searchTimeout);
  • }

6) Detect Whether the User Is Searching (isSearchIncomplete)

The isSearchIncomplete function returns true if the user has changed the input text and a new search must be applied. It compares text (what the user typed) against the component's internal displayValue (the formatted display text of the currently selected value):

Code
  • function isSearchIncomplete(dropDownBox) {
  • let displayValue = dropDownBox.option('displayValue');
  • let text = dropDownBox.option('text') || '';
  • displayValue = displayValue && displayValue.length && displayValue[0];
  • return text !== displayValue;
  • }

7) Focus Management in onOpened

When the popup opens and the DropDownBox raises its onOpened event, move focus into the DataGrid.

The example implementation waits until the grid is ready (first open) or until the popup animation is complete (subsequent opens), then calls grid.focus().

DropDownBoxWithDataGrid.vue
  • function onOpened(e: DxDropDownBoxTypes.OpenedEvent): void {
  • const _gridFirstLoadCompleted = gridFirstLoadCompleted.value;
  • const dropDownBox = e.component;
  • function handleOptionChanged(args: DxDataGridTypes.OptionChangedEvent): void {
  • const grid = args.component;
  • const triggerCondition = _gridFirstLoadCompleted
  • ? args.name === 'opened'
  • : args.name === 'focusedRowKey' || args.name === 'focusedRowIndex';
  • if (triggerCondition) {
  • grid.off('optionChanged', handleOptionChanged);
  • requestAnimationFrame(() => {
  • grid.focus();
  • grid.option('opened', false);
  • });
  • }
  • }
  • dataGridRef.value?.instance?.on('optionChanged', handleOptionChanged);
  • if (gridFirstLoadCompleted.value) {
  • dataGridRef.value?.instance?.option('opened', true);
  • }
  • const { text, value } = dropDownBox.option();
  • const displayValue = dropDownBox.option('displayValue') as string[];
  • const shouldClearSelection = (value && !text) || text !== displayValue[0];
  • if (shouldClearSelection && selectedRowKeys.value?.length) {
  • selectedRowKeys.value = [];
  • }
  • }

8) Reset Component State in onClosed

When the popup closes, the onClosed event restores consistent state if the user typed something but did not confirm a selection.

  • If nothing was loaded, reset the DropDownBox and clear searchValue
  • If a search was in progress (text !== displayValue), auto-select the first row
DropDownBoxWithDataGrid.vue
  • function onClosed(e: DxDropDownBoxTypes.ClosedEvent): void {
  • const dropDownBox = e.component;
  • const hasLoadedItems = dataGridRef.value?.instance?.getVisibleRows().length;
  • const text = dropDownBox.option('text');
  • const displayValue = dropDownBox.option('displayValue') as string[];
  • if (!hasLoadedItems) {
  • dropDownBox.reset('');
  • props.dataSource.searchValue('');
  • props.dataSource.load().catch(() => {});
  • return;
  • }
  • if (text && text !== displayValue[0]) {
  • const firstKey = dataGridRef.value?.instance?.getKeyByRowIndex(0);
  • dropDownValue.value = firstKey ?? null;
  • selectedRowKeys.value = firstKey ? [firstKey] : [];
  • focusedRowKey.value = firstKey ?? null;
  • }
  • }
NOTE
This implementation supports single selection only. To implement multiple selection, use the TagBox component instead.
See Also

Search by Lookup Column (TreeList)

This topic covers search by a lookup column display value in a DropDownBox with an embedded TreeList. Because the search target is a display value from a related dataset, the approach resolves the typed text to matching IDs via the lookup data source, then applies a DataSource.filter on the main data source.

NOTE
For a similar example that does not involve a lookup column, see Search by Field Values (DataGrid).

The full working code is available in the GitHub repository:

View on GitHub

1) Configure DropDownBox to Accept User Input

DropDownList.vue
  • <DxDropDownBox
  • :accept-custom-value="true"
  • value-change-event=""
  • :open-on-field-click="false"
  • ...
  • />

2) Create the Main DataSource for TreeList

Declare a data source for the TreeList.

DropDownList.vue
  • const dataSource = new DataSource({
  • store: AspNetData.createStore({
  • key: 'Task_ID',
  • loadUrl: `${url}/Tasks`,
  • }),
  • });

3) Configure displayExpr

Use displayExpr to define how a selected item appears in the input field.

Because the displayed text depends on lookup data (employee name from a related dataset), pre-load that data and resolve it in displayExpr:

DropDownList.vue
  • const lookupItems = ref<Employee[]>([]);
  •  
  • onMounted(() => {
  • lookupStore.load().then((items: Employee[]) => {
  • lookupItems.value = items;
  • dropDownBoxRef.value?.instance?.repaint();
  • });
  • });
  •  
  • function displayExpr(item: Task): string {
  • if (!lookupItems.value.length) return 'Loading...';
  • if (!item) return '';
  • const employee = lookupItems.value.find(
  • (e) => e.ID === item.Task_Assigned_Employee_ID
  • );
  • if (!employee) return item.Task_Subject || '';
  • return `${employee.Name}: ${item.Task_Subject} (${item.Task_Status})`;
  • }

4) Configure the Embedded TreeList in contentTemplate

Configure the DropDownBox component. Use contentTemplate to render the TreeList. In the TreeList component, activate focusedRowEnabled and set single selection.mode.

DropDownList.vue
  • <template #content>
  • <DxTreeList
  • ref="treeListRef"
  • :data-source="dataSource"
  • has-items-expr="Has_Items"
  • parent-id-expr="Task_Parent_ID"
  • :column-auto-width="true"
  • :word-wrap-enabled="true"
  • :show-borders="true"
  • :height="400"
  • width="100%"
  • :focused-row-enabled="true"
  • v-model:focused-row-key="focusedRowKey"
  • v-model:selected-row-keys="selectedRowKeys"
  • @content-ready="treeListOnContentReady"
  • @key-down="treeListOnKeyDown"
  • @selection-changed="onSelectionChanged"
  • >
  • <DxRemoteOperations :filtering="true" :sorting="true" :grouping="true" />
  • <DxSelection mode="single" />
  • <DxScrolling mode="virtual" />
  • <DxColumn data-field="Task_ID" />
  • <DxColumn data-field="Task_Assigned_Employee_ID" caption="Employee" :min-width="120">
  • <DxLookup :data-source="lookupStore" value-expr="ID" display-expr="Name" />
  • </DxColumn>
  • <DxColumn data-field="Task_Subject" :width="300" />
  • <DxColumn data-field="Task_Start_Date" caption="Start Date" data-type="date" />
  • <DxColumn data-field="Task_Status" caption="Status" />
  • <DxColumn data-field="Task_Due_Date" caption="Due Date" data-type="date" />
  • </DxTreeList>
  • </template>

5) Implement Search in onInput

Use the onInput event to open the dropdown and trigger the search. Because the search targets a lookup column display value, the typed text must first be resolved to matching IDs via the lookup data source, then applied as a DataSource.filter to the main data source:

Code
  • function applySearchFilter(text, lookupField, dataField, searchExprVal, lookupDataSource, dataSource) {
  • // Step 1: find employees whose Name contains the typed text
  • lookupDataSource.load({ filter: [lookupField, 'contains', text] }).done((items) => {
  • const filterParts = [];
  •  
  • // Step 2: optionally also search in a non-lookup field (for example, Task_Subject)
  • if (Array.isArray(searchExprVal)) {
  • filterParts.push([searchExprVal[1], 'contains', text]);
  • }
  •  
  • // Step 3: add an OR condition for each matched employee ID
  • items.forEach((item, index) => {
  • if (filterParts.length > 0 || index > 0) filterParts.push('or');
  • filterParts.push([dataField, '=', item.ID]);
  • });
  •  
  • // Step 4: apply the filter (use a "no-results" sentinel if nothing matched)
  • const filterExpr = filterParts.length > 0 ? filterParts : [dataField, '=', -1];
  • dataSource.filter(filterExpr);
  • dataSource.load();
  • });
  • }
DropDownList.vue
  • function onInput(e: DxDropDownBoxTypes.InputEvent): void {
  • if (searchTimerId) clearTimeout(searchTimerId);
  • const instance = e.component;
  • if (!dropDownBoxOpened.value) dropDownBoxOpened.value = true;
  • if (isSearchIncomplete(instance)) {
  • const text = instance.option('text');
  • if (text) {
  • searchTimerId = setTimeout(() => {
  • applySearchFilter(text, props.searchExprValue, props.dataSource);
  • }, searchTimeoutValue.value);
  • } else {
  • props.dataSource.filter(null);
  • }
  • focusInput();
  • }
  • }

6) Detect Whether the User Is Searching (isSearchIncomplete)

The isSearchIncomplete function returns true if the user has changed the input text and a new search must be applied. It compares text (what the user typed) against the component's internal displayValue (the formatted display text of the currently selected value):

Code
  • function isSearchIncomplete(dropDownBox) {
  • let displayValue = dropDownBox.option('displayValue');
  • let text = dropDownBox.option('text') || '';
  • displayValue = displayValue && displayValue.length && displayValue[0];
  • return text !== displayValue;
  • }

7) Focus Management in onOpened

When the popup opens and the DropDownBox raises its onOpened event, move focus into the TreeList.

The example implementation waits until the TreeList is ready (first open) or until the popup animation completes (subsequent opens), then calls list.focus(). It also clears the TreeList selection when the input text no longer matches the selected value.

DropDownList.vue
  • function onOpened(e: DxDropDownBoxTypes.OpenedEvent): void {
  • const treeListInstance = treeListRef.value?.instance;
  • const dropDownBox = e.component;
  • function handleOptionChanged(args: DxTreeListTypes.OptionChangedEvent): void {
  • const list = args.component;
  • const triggerCondition = listFirstLoadCompleted
  • ? args.name === 'openTrigger'
  • : args.name === 'focusedRowKey' || args.name === 'focusedColumnIndex';
  • if (triggerCondition) {
  • list.off('optionChanged', handleOptionChanged);
  • requestAnimationFrame(() => {
  • list.focus();
  • list.option('openTrigger', 'closed');
  • });
  • }
  • }
  • treeListInstance?.on('optionChanged', handleOptionChanged);
  • if (listFirstLoadCompleted) {
  • treeListInstance?.option('openTrigger', 'opened');
  • }
  • const { text, value: dropDownValue } = dropDownBox.option();
  • const displayValue = dropDownBox.option('displayValue') as string[] | undefined;
  • const shouldClearSelection = (dropDownValue && !text) || text !== displayValue?.[0];
  • if (shouldClearSelection) {
  • selectedRowKeys.value = [];
  • treeListInstance?.pageIndex(0).then(() => {
  • treeListInstance?.option('focusedRowIndex', 0);
  • focusedRowKey.value = FIRST_ROW_KEY;
  • focusInput();
  • }).catch(() => {});
  • }
  • }

8) Reset Component State in onClosed

When the popup closes, the onClosed event restores consistent state if the user typed something but did not confirm a selection. The search state is cleared by calling dataSource.filter(null).

DropDownList.vue
  • function onClosed(e: DxDropDownBoxTypes.ClosedEvent): void {
  • const treeListInstance = treeListRef.value?.instance;
  • const dropDownBox = e.component;
  • const text = dropDownBox.option('text');
  • const displayValue = (dropDownBox.option('displayValue') as string[] | undefined)?.[0];
  • const resetValue = text && text !== displayValue;
  • if (!hasLoadedItems) {
  • value.value = null;
  • selectedRowKeys.value = [];
  • props.dataSource.filter(null);
  • props.dataSource.load().catch(() => {});
  • }
  • if (resetValue && !selectedRowKeys.value.length && treeListInstance) {
  • const firstKey = treeListInstance.getKeyByRowIndex(0) as number;
  • value.value = firstKey;
  • selectedRowKeys.value = [firstKey];
  • focusedRowKey.value = firstKey;
  • }
  • }
NOTE
This implementation supports single selection only. To implement multiple selection, use the TagBox component instead.

Example

See this example for more details: DropDownBox with embedded TreeList.

See Also