Create a custom select component with typeahead built on @angular/cdk in Angular
Native select element is used to create a drop-down list of options for users to choose from but does not support searching and typeahead.
Because of that, there are situations where developers are forced
to create their own select component.
See how you can implement custom select with searching with typehead.
Select implements ControlValueAccessor what means you can bind formControlName or ngModel directive.
Creating overlay
To open an overlay is used @angular/cdk/overlay package.
Thanks to this library all logic to create and position is hidden under nice classes and methods.
Adding a11y
Built Select has support for keyboard shortcuts.
You can open an overlay with Enter, Arrow up or Arrow down.
It has been done thanks to @angular/cdk/a11y library and ActiveDescendantKeyManager.
To close an overlay you can press Escape.
Defining data source
Select require to implement data source.
It is the only way to pass data to select.
In addition to defining the data retrieval source is required to
define a property to bind to control – a way to retrieve a representation of the selected value.
Example data sources
Country data source
The example country data source as directive can be used anywhere in a application
You just need to provide directive to the app-select component
Github repository data source
The example github repository data source as directive can be used anywhere in a application
You just need to provide directive to the app-select component
Option template
To define a view of an option you have to define a template inside app-select.
To have types (ng-template does not provide types) you should create a component with appropriate input.
Separate template for option
In a scenario where you need to have a different template per option, you should put ngIf or ngSwitch into template.
Do you like the content?
Your support helps me continue my work. Please consider making a donation.
Donations are accepted through PayPal or Stripe. You do not need a account to donate. All major credit cards are
accepted.