The Angular CDK is an important toolkit for building Angular applications. We’ve already covered how to display an overlay using the CDK. Today, let’s create a custom list selection feature using CDK ListBox.
Often, HTML dropdowns are too basic to allow for meaningful customization of what gets rendered in the dropdown. This has led to the creation of several custom components, such as Material Select.
But what if you’re not using a library and still need to customize a list of items for your users? Something like this, for instance:
Implementing such a UI with HTML is not very difficult. The complexity of the task comes from getting all the expected behaviors for an accessible experience, such as keyboard interaction and focus management.
This is where the cdkListbox
directive shines. Here’s an example:
The few lines of code in this example add the following select-dropdown-like features to these basic HTML list items:
- A numerical value is associated with the user selection (1, 0, or -1) thanks to
cdkOption
- Typeahead is available. If I click on the list and then type “o” on my keyboard, the “Okay” option gets selected.
- The current selection can be changed using the keyboard’s up and down keys.
And there are many more possibilities to explore. For instance, enabling multiple selections in the list is as easy as adding a cdkListboxMultiple
attribute on our list element:
And now I can do this:
You can see that example in action on Stackblitz here. Another nice feature of the Angular CDK is that all its directives are standalone, so we can import just what we need in our components: