-
Notifications
You must be signed in to change notification settings - Fork 6.8k
Expand file tree
/
Copy pathautocomplete-auto-select-example.ts
More file actions
92 lines (82 loc) · 2.51 KB
/
autocomplete-auto-select-example.ts
File metadata and controls
92 lines (82 loc) · 2.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
Combobox,
ComboboxInput,
ComboboxPopup,
ComboboxPopupContainer,
} from '@angular/aria/combobox';
import {Listbox, Option} from '@angular/aria/listbox';
import {
afterRenderEffect,
ChangeDetectionStrategy,
Component,
computed,
viewChild,
viewChildren,
} from '@angular/core';
import {COUNTRIES} from '../countries';
import {CdkAriaLive} from '@angular/cdk/a11y';
import {OverlayModule} from '@angular/cdk/overlay';
import {FormsModule} from '@angular/forms';
/** @title Autocomplete with auto-select filtering. */
@Component({
selector: 'autocomplete-auto-select-example',
templateUrl: 'autocomplete-auto-select-example.html',
styleUrl: '../autocomplete.css',
imports: [
CdkAriaLive,
Combobox,
ComboboxInput,
ComboboxPopup,
ComboboxPopupContainer,
Listbox,
Option,
OverlayModule,
FormsModule,
],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class AutocompleteAutoSelectExample {
/** The selected value of the combobox. */
listbox = viewChild<Listbox<string>>(Listbox);
/** The options available in the listbox. */
options = viewChildren<Option<string>>(Option);
/** A reference to the ng aria combobox. */
combobox = viewChild<Combobox<string>>(Combobox);
/** A reference to the ng aria combobox input. */
comboboxInput = viewChild<ComboboxInput>(ComboboxInput);
/** The query string used to filter the list of countries. */
query = computed(() => this.comboboxInput()?.value() || '');
/** The list of countries filtered by the query. */
countries = computed(() =>
COUNTRIES.filter(country => country.toLowerCase().startsWith(this.query().toLowerCase())),
);
constructor() {
// Scrolls to the active item when the active option changes.
afterRenderEffect(() => {
if (this.combobox()?.expanded()) {
const option = this.options().find(opt => opt.active());
option?.element.scrollIntoView({block: 'nearest'});
}
});
}
/** Clears the query and the listbox value. */
clear(): void {
this.comboboxInput()?.value.set('');
this.listbox?.()?.values.set([]);
}
/** Handles keydown events on the clear button. */
onKeydown(event: KeyboardEvent): void {
if (event.key === 'Enter') {
this.clear();
this.combobox?.()?.close();
event.stopPropagation();
}
}
}