Angular 7 - заставить событие keydown на div не работать - PullRequest
0 голосов
/ 30 сентября 2019

У меня угловое 7 приложение с формой поиска. При вводе в форму я фильтрую вывод и представляю вывод в виде списка div. При использовании события (щелчка) я могу выбрать и вызвать функцию, но при попытке использовать событие (нажатие клавиши) это не работает.

<input type="text" class="form-control" 
id="licensePlate" 
aria-describedby="licensePlate" 
name="licensePlate" #licensePlate="ngModel" 
required minlength="2" [(ngModel)]="carModel" [ngbTypeahead]="carAutoComplete" 
[inputFormatter]="CarFormatter" 
[resultTemplate]="carTemplate">

Работа с мышью:

<ng-template #carTemplate let-r="result" let-t="term">
    <div (click)="searchCar(r.id)">{{ r.licensePlate }} - {{ r.make }} {{ r.carModel }}</div>
</ng-template>

Не работает с клавиатурой

<ng-template #carTemplate let-r="result" let-t="term">
    <div (keydown)="keyDownFunction($event)" tabindex="0">{{ r.licensePlate }} - {{ r.make }} {{ r.carModel }}</div>
</ng-template>

Вот мой код TS:

carAutoComplete = (text$: Observable<string>) =>
  text$.pipe(
    debounceTime(200),
    distinctUntilChanged(),
    map(term => term.length < 2 ? []
      : this.carsList.filter(v => v.licensePlate.toLowerCase().indexOf(term.toLowerCase()) > -1).slice(0, 10))
  )
  CarFormatter = (x: {licensePlate: string}) => x.licensePlate;

  keyDownFunction(event) {
    console.log('Clicked keyboard:', event);
  }

  searchCar(id: number) {
    this.searchSelected = true;
    this.router.navigate(['car', id]);
  }

Iхотите иметь возможность выбирать автомобиль с помощью мыши и только с клавиатуры.

Ответы [ 2 ]

0 голосов
/ 30 сентября 2019

Получилось, не идеально, вероятно, так как требуется 2 раза нажать клавишу Enter (выберите div из списка, а затем отправьте ввод, но, по крайней мере, работает как ожидалось. Добавлена ​​клавиша ввода:

<input type="text" class="form-control" id="licensePlate" aria-describedby="licensePlate" name="licensePlate" #licensePlate="ngModel" 
required minlength="2" [(ngModel)]="carModel" 
[ngbTypeahead]="carAutoComplete" [inputFormatter]="CarFormatter" [resultTemplate]="carTemplate" 
(keydown)="searchCarKeyboard($event, licensePlate)">

Исоздана новая функция:

searchCarKeyboard(event, licensePlate) {
  if (event.keyCode === 13) {
    if (licensePlate.model.id) {
      const carId = licensePlate.model.id;
      this.searchSelected = true;
      this.router.navigate(['car', carId]);
    }
  }
}
0 голосов
/ 30 сентября 2019

Чтобы иметь событие keydown для таких элементов, как div , p , необходимо использовать атрибут contenteditable .

Таким образом, у вас будет что-то вроде этого:

<ng-template #carTemplate let-r="result" let-t="term">
    <div contenteditable="true" (keydown)="keyDownFunction($event)" tabindex="0">{{ r.licensePlate }} - {{ r.make }} {{ r.carModel }}</div>
</ng-template>
...