AutocompleteField
The AutocompleteField
behaves like a standard text input, with an additional panel of suggested options.
Import
- React
- Angular
- Vue.js
// with @dhl-official/react-library:
import { DhlAutocompleteField } from "@dhl-official/react-library"
// with @dhl-official/ui-libraries/react-library:
import { DhlAutocompleteField } from "@dhl-official/ui-libraries/react-library"
If the DUIL has been installed, you can use the web component directly:
<dhl-autocomplete-field></dhl-autocomplete-field>
// with @dhl-official/vue-library:
import { DhlAutocompleteField } from "@dhl-official/vue-library"
// with @dhl-official/ui-libraries/vue-library:
import { DhlAutocompleteField } from "@dhl-official/ui-libraries/vue-library"
Options to be displayed by the Autocomplete component are required and are to be passed to the options prop as an array.
options = [
{
id: "1",
label: "ARG",
value: "Argentina",
},
{
id: "2",
label: "AUS",
value: "Australia",
},
{
id: "3",
label: "GER",
value: "Germany",
},
];
Guidelines
- By default, the
AutoCompleteField
component filters using thelabel
field value within eachoption
found in the options array. This behaviour occurs in the absence of a definedcustomFilter
prop. - If you choose to omit the
label
field from youroptions
array structure, you need to implement a custom filtering function, passed to thecustomFilter
prop. There, you'll be able to specify upon which key to filter from your options object. - If your options list consists of an array of strings, the component internal business logic will convert it to a data structure that includes the
label
andvalue
fields, assigning to both of them the same value.
Code
- React
- Angular
- Vue.js
<DhlAutocompleteField options={[
{ id: "1", label: "ARG", value: "Argentina"},
{ id: "2", label: "AUS", value: "Australia"},
{ id: "3", label: "GER", value: "Germany" },
]}></DhlAutocompleteField>
<dhl-autocomplete-field [options]="options"></dhl-autocomplete-field>
<dhl-autocomplete-field :options.prop='[
{ id: "1", label: "ARG", value: "Argentina"},
{ id: "2", label: "AUS", value: "Australia"},
{ id: "3", label: "GER", value: "Germany" },
]'></dhl-autocomplete-field>
Interactive Demo
Migrating from DUIL 1.0
- Rename
onBlur
toblurEvent
- Rename
onChange
toinputEvent
- Rename
onOptionSelected
tooptionSelected
- Rename
ariaDescribe
todataAriaDescribedby
- Remove
renderOption
- Remove
isBlock
Readme
Usage
Dhl-autocomplete-field
Snippets of code in HTML and JavaScript to show some of the use cases for the component.
The code is not meant to be executed, but to be used as a reference for the usage of the component.
Angular, React and Vue usages are not included in this documentation, but can be easily derived from the html and javascript code.
default usage with custom event and, default filter function and custom validation
<form novalidate>
<dhl-autocomplete-field
name="autocomplete"
value=""
></dhl-autocomplete-field>
<hr />
<dhl-button
type="reset"
variant="outline"
>reset</dhl-button
>
<dhl-button type="submit">submit</dhl-button>
</form>
<script type="module">
const form = document.querySelector("form");
const options = Array.from(Array(10).keys()).map((i) => ({
value: `opt${i}`,
label: `Option ${i}`,
id: `id${i}`,
}));
const autocomplete = document.querySelector("dhl-autocomplete-field");
autocomplete.options = [...options];
const checkAutocompleteFieldValidity = async () => {
const validationMessageInvalid = "This field is NOT valid";
const validationMessageValid = "This field valid";
const isValid = await autocomplete.checkValidity();
autocomplete.validation = {
type: isValid ? Variants.valid : Variants.invalid,
message: isValid ? validationMessageValid : validationMessageInvalid,
};
};
autocomplete.addEventListener("dhlFocus", console.log);
autocomplete.addEventListener("dhlKeyUp", console.log);
autocomplete.addEventListener("dhlKeyDown", console.log);
autocomplete.addEventListener("dhlInput", console.log);
autocomplete.addEventListener("dhlBlur", async (e) => {
console.log(e);
await checkAutocompleteFieldValidity();
});
form.addEventListener("submit", async (e) => {
e.preventDefault();
await checkAutocompleteFieldValidity();
const data = new FormData(form);
console.log(Object.fromEntries(data));
});
</script>
usage with custom event, custom filter function and custom validation messages
<form novalidate>
<dhl-autocomplete-field
name="autocomplete"
value=""
></dhl-autocomplete-field>
<hr />
<dhl-button
type="reset"
variant="outline"
>reset</dhl-button
>
<dhl-button type="submit">submit</dhl-button>
</form>
<script type="module">
const form = document.querySelector("form");
const options = Array.from(Array(20).keys()).map((i) => ({
value: `opt${i}`,
label: `${i} option`,
id: `id${i}`,
}));
const autocomplete = document.querySelector("dhl-autocomplete-field");
autocomplete.options = [...options];
// custom filter example:
// only filter for values with at least 3 characters.
// if the user types "1 op" the options will be filtered
// to show only the options that contain "1 op" in the label
autocomplete.customFilter = (options, value) =>
value?.length < 3
? options
: options.filter((option) => option.label.includes(value));
const checkAutocompleteFieldValidity = async () => {
const validationMessageInvalid = "This field is NOT valid";
const validationMessageValid = "This field valid";
const isValid = await autocomplete.checkValidity();
autocomplete.validation = {
type: isValid ? Variants.valid : Variants.invalid,
message: isValid ? validationMessageValid : validationMessageInvalid,
};
};
autocomplete.addEventListener("dhlFocus", console.log);
autocomplete.addEventListener("dhlKeyUp", console.log);
autocomplete.addEventListener("dhlKeyDown", console.log);
autocomplete.addEventListener("dhlInput", console.log);
autocomplete.addEventListener("dhlBlur", async (e) => {
console.log(e);
await checkAutocompleteFieldValidity();
});
form.addEventListener("submit", async (e) => {
e.preventDefault();
await checkAutocompleteFieldValidity();
const data = new FormData(form);
console.log(Object.fromEntries(data));
});
</script>
Properties
Property | Attribute | Description | Type | Default |
---|---|---|---|---|
blurEvent | -- | [DEPRECATED] Use dhlBlur event instead.An optional onBlur callback handler. | (event?: FocusEvent) => void | undefined |
customFilter | -- | An optional callback handler that accepts the options and input data, used for custom filtering. If this function is not passed, by default, filtering will happen on "label" key of the item if its an object or the actual value if the item is a primitive data type | (options: unknown, value: string) => Option[] | undefined |
dataAriaDescribedby | data-aria-describedby | An optional prop defining the list of reference IDs (separated by spaces), recommended when you want to an error message on your field. | string | When autocomplete results are available use up and down arrows to review and enter to select. Touch device users, explore by touch or with swipe gestures. |
dataAriaLabel | data-aria-label | An optional prop defining the text read by the screen reader to represent the component; use this if you need different text to be read from label. | string | undefined |
dataClassName | data-class-name | An optional class name prop for the component. | string | undefined |
dataId | id | An optional prop. Gives a valid HTML ID attribute value for the component. | string | dhl-autocomplete-field-${getRandomString()} |
dataTestid | data-testid | An optional prop. The test id attached to the component as a data-testid attribute. | string | undefined |
inputEvent | -- | [DEPRECATED] - Use dhlInput event insteadAn optional onChange callback handler, used to hold the logic for filtering Autocomplete options - | (event: InputEvent) => void | undefined |
isBlock | is-block | [DEPRECATED] An optional prop flag to control if the component is rendered as block or inline-block element. | boolean | undefined |
isDisabled | disabled | An optional flag to define if the component is disabled. | boolean | false |
name | name | An optional value to be set to the element HTML name attribute. It takes any valid value that can be used for the name attribute of an HTMLInputElement. | string | "autocomplete" |
numberOfOptionsCopy | number-of-options-copy | An optional prop holding the number of options in Autocomplete to be read by screen readers | string | "results available below" |
openOnFocus | open-on-focus | An optional prop when set to true, the option list will be shown on input focus. | boolean | false |
optionSelected | -- | [DEPRECATED] - Use dhlOptionSelected event insteadAn optional callback handler, used to handle "an option selected" event - | (option: Option) => void | undefined |
options (required) | -- | A REQUIRED Autocomplete options prop array which holds the available options to select within the Autocomplete component | (string \| Option)[] | undefined |
required | required | An optional prop to flag the component as required within a form context. | boolean | undefined |
searchIcon | search-icon | An optional prop flag to define if the search icon is displayed. | boolean | undefined |
validation | -- | An optional object to set-up a custom components validation state. Required Fields: type | { type: Variants.valid \| Variants.invalid \| Variants.note; message?: string; } | undefined |
value | value | An optional prop defining the value of the component which is taken when a form is submitted. | string | undefined |
variant | -- | An optional prop to select a component design variant. Required Fields type | { label?: string; placeholder?: string; type: Variants.animated \| Variants.static; } | undefined |
Events
Event | Description | Type |
---|---|---|
dhlOptionSelected | Event emitted when an option is selected. | CustomEvent<any> |
Methods
checkValidity() => Promise<boolean>
Checks the validity of the input field.
Returns
Type: Promise<boolean>
A promise that resolves to true if the input field is valid, otherwise false.
getInputElement() => Promise<HTMLInputElement>
Retrieves the input element asynchronously.
Returns
Type: Promise<HTMLInputElement>
A promise that resolves to the input element.
getValidationMessage() => Promise<string>
Retrieves the validation message for the input field.
Returns
Type: Promise<string>
A promise that resolves to a string representing the validation message.
reportValidity() => Promise<boolean>
Reports the validity of the input field.
Returns
Type: Promise<boolean>
A promise that resolves to a boolean indicating whether the input field is valid.
setValidity(validity: ValidityState, validationMessage?: string) => Promise<void>
Sets the validity state of the input field.
Parameters
Name | Type | Description |
---|---|---|
validity | ValidityState | - The validity state to set. |
validationMessage | string | - An optional validation message to set. |
Returns
Type: Promise<void>
A Promise that resolves when the validity state is set.
willValidate() => Promise<boolean>
Returns a promise that resolves to true if the element will successfully validate, or false otherwise.
Returns
Type: Promise<boolean>
A promise that resolves to a boolean value indicating whether the element will validate.
Dependencies
Depends on
Graph
Built by DHL User Interface Library Team!