我正在使用ng select: https://www.npmjs.com/package/@ng-select/ng-select
StackBlitz: https://stackblitz.com/edit/angular-rvo39c?file=src%2Fforms-with-options-example.component.ts
我希望能够用箭头Listbox
或UP
突出显示DOWN
中的对象,然后在按下箭头{{1}时使突出显示的项目selected
}或RIGHT
。
我尝试使用事件LEFT
和事件keydownInDropdown
来执行此操作。
onDropDownChange
在keydownInDropdown
之前被触发。
另一个适用于我的解决方案:
用箭头onDropDownChange
或Listbox
高亮显示UP
中的对象,然后在第一次单击DOWN
时选择对象。
如果没有任何更改,请第二次单击enter
。
答案 0 :(得分:0)
整天工作后提出以下解决方案。当您在选择选项时单击向右或向左箭头键时,它将被选中。(您可以替换堆栈代码中的整个代码。我选择了单个代码,也可以根据需要选择多个代码。)
component.html代码
<form [formGroup]="heroForm" novalidate>
<div class="form-row">
<div class="form-group col-md-6">
<ng-select [virtualScroll]="false" [multiple]="false" [keyDownFn]="keydownInDropdown"
(keydown)="makeChoice($event)" #ngSelect
> // taking its reference by #ngSelect & calling "makeChoice" method when any keyboard clicks are happening.
// there is no need of ngModel so i removed it from the code.
<ng-option *ngFor="let car of cars" [value]="car.id"
>{{car.name}}</ng-option>
<ng-option [value]="'custom'">Custom</ng-option>
</ng-select>
<br/>Selected car ID: {{selectedCars | json}}
</div>
</div>
component.ts代码
import { Component, OnInit,ElementRef,HostListener,ViewChildren } from '@angular/core';
import { FormBuilder, FormGroup } from '@angular/forms';
@Component({
selector: 'forms-with-options-example',
templateUrl: './forms-with-options-example.component.html',
styleUrls: ['./forms-with-options-example.component.scss']
})
export class FormsWithOptionsExampleComponent implements OnInit {
constructor(
private fb: FormBuilder,private el:ElementRef) {
}
@ViewChildren('ngSelect') ngSelect:ElementRef;
selectedCars = [3];
cars = [
{ id: 1, name: 'Volvo' },
{ id: 2, name: 'Saab' },
{ id: 3, name: 'Opel' },
{ id: 4, name: 'Audi' },
];
keydownInDropdown(event)
{
if (event.keyCode == 13)
{
// set highlighted value as selected value. (default)
console.log(event);
}
if (event.keyCode == 37 || event.keyCode == 39)
{
// set highlighted value as selected value.
console.log(event);
}
// console.log("keydown is ",event)
}
ngOnInit() {
}
makeChoice(e) {
if(e.key==='ArrowRight' || e.key==='ArrowLeft') {
var totalOptions = this.ngSelect["first"].dropdownPanel.contentElementRef.nativeElement.children;
console.log("total opetions are ",totalOptions);
var i;
for(i=0;i<totalOptions.length;i++) {
if(totalOptions[i].classList.value.includes('ng-option-marked')) {
// console.log("selected index is ",i);
this.selectedCars = i;
totalOptions[i].click();
}
}
}
}
}