After working whole day came up with following solution. When you click right or left arrow keys while selecting options it will be selected.(you can replace whole code in your stackblitz. I made it for single select you can also make it for multi-select based on your requirement.)
component.html code
<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 code
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();
}
}
}
}
}