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.

You can view the source code for this project by following this link: GitHub

Demo

Integration with forms

Select implements ControlValueAccessor what means you can bind formControlName or ngModel directive.

1
import { ControlValueAccessor } from "@angular/forms";
2
3
@Component({
4
selector: "app-select",
5
template: `
6
<form [formGroup]="form">
7
<app-select formControlName="githubProfile">
8
<!-- ... -->
9
</app-select>
10
</form>
11
`,
12
/* */
13
})
14
export class SelectComponent implements ControlValueAccessor {
15
/* */
16
}

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.

1
import { Overlay } from "@angular/cdk/overlay";
2
3
@Component({
4
selector: "app-select",
5
/* */
6
})
7
export class SelectComponent /* */ {
8
private overlay = inject(Overlay);
9
private elementRef = inject<ElementRef<HTMLElement>>(ElementRef);
10
11
private createOverlay(): OverlayRef {
12
const positionStrategy = this.overlay
13
.position()
14
.flexibleConnectedTo(this.elementRef)
15
.withPositions([{ originX: "start", originY: "top", overlayX: "start", overlayY: "top" }]);
16
17
return this.overlay.create({
18
hasBackdrop: true,
19
backdropClass: "",
20
positionStrategy,
21
minWidth: this.elementRef.nativeElement.clientWidth,
22
});
23
}
24
}

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.

1
import { ActiveDescendantKeyManager } from "@angular/cdk/a11y";
2
3
@Component({
4
selector: "app-select",
5
/* */
6
})
7
export class SelectComponent /* */ {
8
private keyManager!: ActiveDescendantKeyManager<HightlightableOptionDirective>;
9
10
ngAfterViewInit(): void {
11
this.keyManager = new ActiveDescendantKeyManager(this.optionElsQuery).withHomeAndEnd().withWrap().withPageUpDown();
12
}
13
}

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.

1
export abstract class SelectDataSource<T> {
2
abstract getOptions(searchValue$: Observable<string>): Observable<T[]>;
3
abstract getBindedValue(value: T): unknown;
4
}
1
@Component({
2
selector: "app-select",
3
/* ... */
4
})
5
export class SelectComponent implements ControlValueAccessor, AfterViewInit, OnDestroy {
6
private selectDataSource = inject(SelectDataSource);
7
protected options$ = this.selectDataSource.getOptions(this.searchedValue$);
8
9
/* ... */
10
11
selectOption(option: unknown): void {
12
const bindedValue = this.selectDataSource.getBindedValue(option);
13
this.emitValue(bindedValue);
14
/* ... */
15
}
16
17
registerOnChange(fn: any): void {
18
this.emitValue = fn;
19
}
20
21
/* ... */
22
}

Example data sources

Country data source

The example country data source as directive can be used anywhere in a application

1
@Directive({
2
selector: "[countryDataSource]",
3
standalone: true,
4
providers: [
5
{
6
provide: SelectDataSource,
7
useExisting: CountryDataSourceDirective,
8
},
9
],
10
})
11
export class CountryDataSourceDirective implements SelectDataSource<Country> {
12
private service = inject(CountryService);
13
14
getOptions(searchValue$: Observable<string>) {
15
return searchValue$.pipe(
16
switchMap((searchValue) =>
17
this.service.countries$.pipe(
18
map((countries) => countries.filter((country) => country.name.includes(searchValue)).slice(0, 15)),
19
),
20
),
21
);
22
}
23
24
getBindedValue(value: Country): unknown {
25
return value.code;
26
}
27
}

You just need to provide directive to the app-select component

1
<app-select countryDataSource formControlName="country">
2
<!-- ... -->
3
</app-select>

Github repository data source

The example github repository data source as directive can be used anywhere in a application

1
@Directive({
2
selector: "[repositoryDataSource]",
3
standalone: true,
4
providers: [
5
{
6
provide: SelectDataSource,
7
useExisting: RepositoryDataSourceDirective,
8
},
9
],
10
})
11
export class RepositoryDataSourceDirective implements SelectDataSource<RepositoryItem> {
12
private service = inject(RepositoryService);
13
14
getOptions(searchValue$: Observable<string>) {
15
return searchValue$.pipe(
16
debounceTime(500),
17
switchMap((searchValue) => this.service.repositories({ searchValue })),
18
);
19
}
20
21
getBindedValue(value: RepositoryItem): string {
22
return value.name;
23
}
24
}

You just need to provide directive to the app-select component

1
<app-select repositoryDataSource formControlName="githubProfile">
2
<!-- ... -->
3
</app-select>

Option template

To define a view of an option you have to define a template inside app-select.

1
@Component({
2
selector: "app-select",
3
template: `
4
<!-- Fragment of app-select template to display available options -->
5
6
<li *ngFor="let option of options$ | async">
7
<ng-template
8
[ngTemplateOutlet]="optionTemplateDirective.template"
9
[ngTemplateOutletContext]="{ $implicit: option }"
10
></ng-template>
11
</li>
12
13
<!-- ... -->
14
`,
15
/* ... */
16
})
17
export class SelectComponent /* */ {
18
// Fragment of app-select logic to get provided template
19
@ContentChild(OptionTemplateDirective, { static: true }) optionTemplateDirective!: OptionTemplateDirective;
20
private selectDataSource = inject(SelectDataSource);
21
protected options$ = this.selectDataSource.getOptions(this.searchedValue$);
22
23
/* ... */
24
}
1
<!-- Example of option template -->
2
3
<app-select someDataSource>
4
<ng-content *appOptionTemplate="let item">{{ item | json }}</ng-content>
5
</app-select>

To have types (ng-template does not provide types) you should create a component with appropriate input.

1
@Component({
2
selector: "app-country-select-option",
3
template: ` <!-- ... --> `,
4
styles: [
5
/* ... */
6
],
7
standalone: true,
8
})
9
export class CountrySelectOptionComponent {
10
@Input({ required: true }) data!: Country;
11
}
1
<app-select countryDataSource>
2
<app-country-select-option *appOptionTemplate="let item" [data]="item" />
3
</app-select>

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.

1
<app-select someDataSource>
2
<ng-container *appOptionTemplate="let item">
3
<ng-container *ngIf="item.code === 'CITY'">
4
<!-- Some city template -->
5
</ng-container>
6
<ng-container *ngIf="item.code === 'COUNTRY'">
7
<!-- Some country template -->
8
</ng-container>
9
</ng-container>
10
</app-select>

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.

Leave a comment