Reputation: 15
I was unable to achieve my goal of picking options in an angular autocomplete dropdown that I created using this tutorial. This is what the component looks like now: Dropdown with focus on hover
The dropdown options can be picked by clicking on them and they end up on the input field. I would also like to be able to pick the options by arrow keys, but am unable to do it. My code looks like this:
autocomplete-select.component.html
<div class="form-group row" clickOutside (clickOutside)="closeAllocationDropDown()" class="pos-rel">
<input class="form-control" type="text" id="allocation" placeholder="Zadajte časový záznam" formControlName="allocation" (click)="toggleAllocationDropDown()" autofocus="autofocus">
<div *ngIf="showAllocationDropdown" class="dropdown" >
<div>
<div (click)="selectAllocation(a.name)" class="allocation" *ngFor="let a of allocations | filterAllocation: getAllocationValue()">
{{a.name}}
</div>
</div>
</div>
</div>
autocomplete-select.component.ts
toggleAllocationDropDown() {
this.showAllocationDropdown = !this.showAllocationDropdown;
}
closeAllocationDropDown() {
this.showAllocationDropdown = false;
}
getAllocationValue() {
return this.selectForm.value.allocation;
}
selectAllocation(value: string) {
this.selectForm.controls['allocation'].setValue(value);
this.showAllocationDropdown = false;
}
autocomplete-select.component.scss
.dropdown {
position:absolute;
z-index:1;
//max-width:100%;
width:100%;
max-height:300px;
background:white;
overflow-y:auto;
}
.pos-rel {
position: relative;
}
.allocation{
padding:10py;
font-family:sans-serif;
color:black;
background-color:$color-soft-grey;
}
.allocation:hover{
background-color:$color-text;
}
input {
cursor: pointer;
width: 100%;
padding: 5px;
}
I imagine I need to create a directive for setting the focus on the dropdown option, but I'm not exactly sure how to research these options.
Upvotes: 0
Views: 2883
Reputation:
You can use keyup events to select what you want :
(keyup.arrowup)="selectPrevious()"
(keyup.arrowdown)="selectNext()"
Upvotes: 1