wdt-combobox
Version:
82 lines (76 loc) • 2.93 kB
text/typescript
import { Component, OnInit, Input, Output, EventEmitter, ElementRef } from "@angular/core";
export class ComboboxMultipleComponent implements OnInit {
placeholder: string = 'Choose An Item ....';
selectedItems = [];
items: any[] = [];
name: string;
search: string = '';
focusedIndex = 0;
constructor(private element: ElementRef) { this.name = `combobox-${Math.round(Math.random() * 10000)}-`; }
ngOnInit(): void {}
open() {
if(!this.element.nativeElement.classList.contains('open')) {
this.element.nativeElement.classList.add('open');
let items = this.getItems();
}
}
close() {
if(this.element.nativeElement.classList.contains('open')) {
this.element.nativeElement.classList.remove('open');
}
}
add(item: any) {
item.checked = true;
this.selectedItems.push(item);
this.focus();
}
remove(item: any) {
item.checked = false;
let index = this.selectedItems.findIndex(value => { return value.value == item.value; });
if(index > -1) this.selectedItems.splice(index,1);
this.focus();
}
toggle(item: any) {
let index = this.selectedItems.findIndex(value => { return value.value == item.value; });
if(index > -1) {
item.checked = false;
this.selectedItems.splice(index,1);
}
else {
item.checked = true;
this.selectedItems.push(item);
}
this.focus();
}
getItems(): any[] {
return this.items.filter((value) => { return value.text.toLowerCase().indexOf(this.search) > -1; });
}
onkeyup(e: KeyboardEvent) {
if (e.keyCode >= 37 && e.keyCode <= 40) {
if (e.keyCode == 38) this.focusedIndex--;
if (e.keyCode == 40) this.focusedIndex++;
this.open();
let ul = this.element.nativeElement.querySelector('ul.items');
let li = ul.querySelector(`li:nth-child(${this.focusedIndex + 1})`);
if(li) ul.scrollTop = li.offsetTop;
}
let items = this.getItems();
if (this.focusedIndex < 0) this.focusedIndex = 0;
if (this.focusedIndex >= items.length) this.focusedIndex = items.length - 1;
if (e.keyCode == 13) {
e.preventDefault();
this.toggle(items[this.focusedIndex]);
}
}
focus() { this.element.nativeElement.querySelector('.search>input').focus(); }
onblur() {
if (this.element.nativeElement.querySelectorAll(':hover').length == 0) {
this.close();
}
}
}