Add Dropdown Prototype

This commit is contained in:
copecone committed 2026-03-10 15:19:15 +09:00
1 parent c9461bd910
commit 9f4ed96190
5 files changed
+252 -172

No files matched your search

+92
View File
@@ -0,0 +1,92 @@
import { Component, input, model, output, signal, HostListener, ElementRef } from '@angular/core'
import { CommonModule } from '@angular/common'
export interface DropdownOption {
label: string;
value: any;
}
@Component({
selector: 'dropdown',
standalone: true,
imports: [CommonModule],
templateUrl: './dropdown.html',
styleUrl: './dropdown.scss',
host: {
'role': 'combobox',
'aria-haspopup': 'listbox',
'[attr.aria-expanded]': 'isOpen()',
'[class.open]': 'isOpen()',
'tabindex': '0',
'(click)': 'toggle()',
'(keydown.enter)': 'toggle()',
'(keydown.space)': 'onSpaceDown($event)',
'(keydown.escape)': 'close()',
'(keydown.arrowdown)': 'onArrowDown($event)',
'(keydown.arrowup)': 'onArrowUp($event)'
}
})
export class Dropdown {
options = input<DropdownOption[]>([]);
placeholder = input<string>('Select an option');
selectedValue = model<any>(null);
change = output<any>();
isOpen = signal(false);
focusedIndex = signal(-1);
constructor(private el: ElementRef) {}
toggle() {
this.isOpen.update(v => !v);
if (this.isOpen()) {
this.focusedIndex.set(this.options().findIndex(o => o.value === this.selectedValue()));
}
}
close() {
this.isOpen.set(false);
this.focusedIndex.set(-1);
}
selectOption(option: DropdownOption) {
this.selectedValue.set(option.value);
this.change.emit(option.value);
this.close();
}
onSpaceDown(event: Event) {
event.preventDefault();
this.toggle();
}
onArrowDown(event: Event) {
event.preventDefault();
if (!this.isOpen()) {
this.toggle();
return;
}
this.focusedIndex.update(i => (i + 1) % this.options().length);
}
onArrowUp(event: Event) {
event.preventDefault();
if (!this.isOpen()) {
this.toggle();
return;
}
this.focusedIndex.update(i => (i - 1 + this.options().length) % this.options().length);
}
@HostListener('document:click', ['$event'])
onDocumentClick(event: MouseEvent) {
if (!this.el.nativeElement.contains(event.target)) {
this.close();
}
}
get selectedLabel(): string {
const selected = this.options().find(o => o.value === this.selectedValue());
return selected ? selected.label : this.placeholder();
}
}