Angular 7-使div上的keydown事件不起作用

问题描述 投票:0回答:2

我有带有搜索表单的angular 7应用。在输入表单时,我正在过滤输出并将输出显示为div的列表。使用(click)事件时,我可以选择并触发函数,但是当尝试使用(keydown)事件时,它不起作用。

<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]);
  }

我希望只能使用鼠标和键盘来选择汽车。

angular keydown
2个回答
0
投票

为了使divp等元素上具有keydown事件,必须使用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>

0
投票

使其正常运行,可能不理想,可能需要按两次Enter键(从列表中选择div,然后提交输入,但至少能按预期运行。在输入中添加了keydown:

<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]);
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.