ComboBox
Description
<vaadin-combo-box>
is a web component for choosing a value from a filterable list of options
presented in a dropdown overlay. The options can be provided as a list of strings or objects
by setting items
property on the element.
<vaadin-combo-box id="combo-box"></vaadin-combo-box>
document.querySelector('#combo-box').items = ['apple', 'orange', 'banana'];
When the selected value
is changed, a value-changed
event is triggered.
Item rendering
To customize the content of the <vaadin-combo-box-item>
elements placed in the dropdown, use
renderer
property which accepts a function.
The renderer function is called with root
, comboBox
, and model
as arguments.
Generate DOM content by using model
object properties if needed, and append it to the root
element. The comboBox
reference is provided to access the combo-box element state. Do not
set combo-box properties in a renderer
function.
const comboBox = document.querySelector('#combo-box');
comboBox.items = [{'label': 'Hydrogen', 'value': 'H'}];
comboBox.renderer = (root, comboBox, model) => {
const item = model.item;
root.innerHTML = `${model.index}: ${item.label} <b>${item.value}</b>`;
};
Renderer is called on the opening of the combo-box and each time the related model is updated.
Before creating new content, it is recommended to check if there is already an existing DOM
element in root
from a previous renderer call for reusing it. Even though combo-box uses
infinite scrolling, reducing DOM operations might improve performance.
The following properties are available in the model
argument:
Property | Type | Description |
---|---|---|
index |
Number | Index of the item in the items array |
item |
String or Object | The item reference |
selected |
Boolean | True when item is selected |
focused |
Boolean | True when item is focused |
Lazy Loading with Function Data Provider
In addition to assigning an array to the items property, you can alternatively use the
dataProvider
function property.
The <vaadin-combo-box>
calls this function lazily, only when it needs more data
to be displayed.
Note that when using function data providers, the total number of items needs to be set manually. The total number of items can be returned in the second argument of the data provider callback:
comboBox.dataProvider = async (params, callback) => {
const API = 'https://demo.vaadin.com/demo-data/1.0/filtered-countries';
const { filter, page, pageSize } = params;
const index = page * pageSize;
const res = await fetch(`${API}?index=${index}&count=${pageSize}&filter=${filter}`);
if (res.ok) {
const { result, size } = await res.json();
callback(result, size);
}
};
Styling
The following custom properties are available for styling:
Custom property | Description | Default |
---|---|---|
--vaadin-field-default-width |
Default width of the field | 12em |
--vaadin-combo-box-overlay-width |
Width of the overlay | auto |
--vaadin-combo-box-overlay-max-height |
Max height of the overlay | 65vh |
<vaadin-combo-box>
provides the same set of shadow DOM parts and state attributes as <vaadin-text-field>
.
See <vaadin-text-field>
for the styling documentation.
In addition to <vaadin-text-field>
parts, the following parts are available for theming:
Part name | Description |
---|---|
toggle-button |
The toggle button |
overlay |
The overlay container |
content |
The overlay content |
loader |
The loading indicator shown while loading items |
In addition to <vaadin-text-field>
state attributes, the following state attributes are available for theming:
Attribute | Description |
---|---|
opened |
Set when the combo box dropdown is open |
loading |
Set when new items are expected |
Internal components
In addition to <vaadin-combo-box>
itself, the following internal
components are themable:
<vaadin-combo-box-item>
- has the same API as<vaadin-item>
.
See Styling Components documentation.
Properties
accessibleName
Type: string | null | undefined
String used to label the component to screen reader users.
accessibleNameRef
Type: string | null | undefined
Id of the element used as label of the component to screen reader users.
allowCustomValue
Type: boolean
If true
, the user can input a value that is not present in the items list.
value
property will be set to the input value in this case.
Also, when value
is set programmatically, the input value will be set
to reflect that value.
allowedCharPattern
Type: string
A pattern matched against individual characters the user inputs.
When set, the field will prevent:
keydown
events if the entered key doesn't match/^allowedCharPattern$/
paste
events if the pasted text doesn't match/^allowedCharPattern*$/
drop
events if the dropped text doesn't match/^allowedCharPattern*$/
For example, to allow entering only numbers and minus signs, use:
allowedCharPattern = "[\\d-]"
autofocus
Type: boolean
Specify that this control should have input focus when the page loads.
autoOpenDisabled
Type: boolean | null | undefined
Set true to prevent the overlay from opening automatically.
autoselect
Type: boolean
If true, the input text gets fully selected when the field is focused using click or touch / tap.
clearButtonVisible
Type: boolean
Set to true to display the clear icon which clears the input.
It is up to the component to choose where to place the clear icon:
in the Shadow DOM or in the light DOM. In any way, a reference to
the clear icon element should be provided via the clearElement
getter.
dataProvider
Type: ComboBoxDataProvider<any> | null | undefined
Function that provides items lazily. Receives arguments params
, callback
params.page
Requested page index
params.pageSize
Current page size
params.filter
Currently applied filter
callback(items, size)
Callback function with arguments:
items
Current page of itemssize
Total number of items.
See also: ComboBoxDataProvider
disabled
Type: boolean
If true, the user cannot interact with this element.
errorMessage
Type: string | null | undefined
Error to show when the field is invalid.
filter
Type: string
Filtering string the user has typed into the input field.
filteredItems
Type: any[] | undefined
A subset of items, filtered based on the user input. Filtered items
can be assigned directly to omit the internal filtering functionality.
The items can be of either String
or Object
type.
helperText
Type: string | null | undefined
String used for the helper text.
invalid
Type: boolean
Set to true when the field is invalid.
itemClassNameGenerator
Type: (item: any) => string
A function used to generate CSS class names for dropdown items based on the item. The return value should be the generated class name as a string, or multiple class names separated by whitespace characters.
itemIdPath
Type: string | null | undefined
Path for the id of the item. If items
is an array of objects,
the itemIdPath
is used to compare and identify the same item
in selectedItem
and filteredItems
(items given by the
dataProvider
callback).
itemLabelPath
Type: string
Path for label of the item. If items
is an array of objects, the
itemLabelPath
is used to fetch the displayed string label for each
item.
The item label is also used for matching items when processing user input, i.e., for filtering and selecting items.
items
Type: any[] | undefined
A full set of items to filter the visible options from.
The items can be of either String
or Object
type.
itemValuePath
Type: string
Path for the value of the item. If items
is an array of objects, the
itemValuePath:
is used to fetch the string value for the selected
item.
The item value is used in the value
property of the combo box,
to provide the form value.
label
Type: string | null | undefined
The label text for the input node. When no light dom defined via [slot=label], this value will be used.
loading
Type: boolean
When set to true
, "loading" attribute is added to host and the overlay element.
manualValidation
Type: boolean
Set to true to enable manual validation mode. This mode disables automatic
constraint validation, allowing you to control the validation process yourself.
You can still trigger constraint validation manually with the validate()
method
or use checkValidity()
to assess the component's validity without affecting
the invalid state. In manual validation mode, you can also manipulate
the invalid
property directly through your application logic without conflicts
with the component's internal validation.
name
Type: string
The name of this field.
opened
Type: boolean
True if the dropdown is open, false otherwise.
pageSize
Type: number
Number of items fetched at a time from the dataprovider.
pattern
Type: string
A regular expression that the value is checked against. The pattern must match the entire value, not just some subset.
placeholder
Type: string
A hint to the user of what can be entered in the field.
readonly
Type: boolean
When present, it specifies that the field is read-only.
renderer
Type: ComboBoxRenderer<any> | null | undefined
Custom function for rendering the content of every item. Receives three arguments:
root
The<vaadin-combo-box-item>
internal container DOM element.comboBox
The reference to the<vaadin-combo-box>
element.model
The object with the properties related with the rendered item, contains:model.index
The index of the rendered item.model.item
The item.
See also: ComboBoxRenderer
required
Type: boolean
Specifies that the user must fill in a value.
selectedItem
Type: any
The selected item from the items
array.
size
Type: number | undefined
Total number of items.
title
Type: string
The text usually displayed in a tooltip popup when the mouse is over the field.
value
Type: string
The value of the field.
Methods
cancel
Type: any
Reverts back to original value.
checkValidity
Type: () => boolean
Returns true if the field value satisfies all constraints (if any).
clear
Type: () => void
Clear the value of the field.
clearCache
Type: () => void
Clears the cached pages and reloads data from dataprovider when needed.
close
Type: () => void
Closes the dropdown list.
open
Type: () => void
Opens the dropdown list.
requestContentUpdate
Type: () => void
Requests an update for the content of items.
While performing the update, it invokes the renderer (passed in the renderer
property) once an item.
It is not guaranteed that the update happens immediately (synchronously) after it is requested.
validate
Type: () => boolean
Validates the field and sets the invalid
property based on the result.
The method fires a validated
event with the result of the validation.
Events
change
Type: ComboBoxChangeEvent
Fired when the user commits a value change.
custom-value-set
Type: ComboBoxCustomValueSetEvent
Fired when the user sets a custom value.
filter-changed
Type: ComboBoxFilterChangedEvent
Fired when the filter
property changes.
input
Type: CustomEvent
Fired when the value is changed by the user: on every typing keystroke, and the value is cleared using the clear button.
invalid-changed
Type: ComboBoxInvalidChangedEvent
Fired when the invalid
property changes.
opened-changed
Type: ComboBoxOpenedChangedEvent
Fired when the opened
property changes.
selected-item-changed
Type: ComboBoxSelectedItemChangedEvent
Fired when selected item changes.
vaadin-combo-box-dropdown-closed
Type: CustomEvent
Fired after the vaadin-combo-box-overlay
closes.
vaadin-combo-box-dropdown-opened
Type: CustomEvent
Fired after the vaadin-combo-box-overlay
opens.
validated
Type: ComboBoxValidatedEvent
Fired whenever the field is validated.
value-changed
Type: ComboBoxValueChangedEvent
Fired when the value changes.
Types
ComboBoxChangeEvent
/**
* Fired when the user commits a value change.
*/
export type ComboBoxChangeEvent<TItem> = Event & {
target: ComboBox<TItem>;
};
ComboBoxCustomValueSetEvent
/**
* Fired when the user sets a custom value.
*/
export type ComboBoxCustomValueSetEvent = CustomEvent<string>;
ComboBoxDataProvider
export type ComboBoxDataProvider<TItem> = (
params: ComboBoxDataProviderParams,
callback: ComboBoxDataProviderCallback<TItem>,
) => void;
ComboBoxDataProviderCallback
export type ComboBoxDataProviderCallback<TItem> = (items: TItem[], size?: number) => void;
ComboBoxDataProviderParams
export interface ComboBoxDataProviderParams {
page: number;
pageSize: number;
filter: string;
}
ComboBoxFilterChangedEvent
/**
* Fired when the `filter` property changes.
*/
export type ComboBoxFilterChangedEvent = CustomEvent<{ value: string }>;
ComboBoxInvalidChangedEvent
/**
* Fired when the `invalid` property changes.
*/
export type ComboBoxInvalidChangedEvent = CustomEvent<{ value: boolean }>;
ComboBoxItemModel
export interface ComboBoxItemModel<TItem> {
index: number;
item: TItem;
selected: boolean;
focused: boolean;
}
ComboBoxItemRenderer
export type ComboBoxItemRenderer<TItem, TOwner> = (
root: HTMLElement,
owner: TOwner,
model: ComboBoxItemModel<TItem>,
) => void;
ComboBoxOpenedChangedEvent
/**
* Fired when the `opened` property changes.
*/
export type ComboBoxOpenedChangedEvent = CustomEvent<{ value: boolean }>;
ComboBoxRenderer
export type ComboBoxRenderer<TItem> = ComboBoxItemRenderer<TItem, ComboBox<TItem>>;
ComboBoxSelectedItemChangedEvent
/**
* Fired when the `selectedItem` property changes.
*/
export type ComboBoxSelectedItemChangedEvent<TItem> = CustomEvent<{ value: TItem | null | undefined }>;
ComboBoxValidatedEvent
/**
* Fired whenever the field is validated.
*/
export type ComboBoxValidatedEvent = CustomEvent<{ valid: boolean }>;
ComboBoxValueChangedEvent
/**
* Fired when the `value` property changes.
*/
export type ComboBoxValueChangedEvent = CustomEvent<{ value: string }>;