通过键盘箭头

时间:2017-12-19 14:54:07

标签: angular keyboard click viewchild

目前,我可以通过css类" message-list-active"来查看列表中的每条消息。按向上和向下箭头键。当我点击行时,我触发点击功能并传递消息对象。但是当按下箭头键时似乎无法点击该元素,我试图通过#fire点击它,但它只点击第一个元素并赢得了'请允许我进入下一个列表。

app.html

<div #fire *ngFor="let message of messages; let i=index" 
           (click)="addMessage(message); activeIndex = i"

  [ngClass]="{'message-list-active': activeIndex === i  }">
     {{message}}
  </div>

component.ts

 messages;  // we have date stored here
 activeIndex = 0;

  onAddtoMessage(message) {
    message.active = !message.active;

}

  @ViewChild('fire') fileInput: ElementRef;

  @HostListener("document:keydown", ['$event']) 
  doSomething(event: KeyboardEvent): void {


    if (event.code == "ArrowUp" && this.activeIndex > 0) {
        this.activeIndex--
        this.fileInput.nativeElement.click()
    }
    if (event.code == "ArrowDown" && this.activeIndex < this.messages.length - 1) {
        this.activeIndex++
        this.fileInput.nativeElement.click()
    }
   }

如何使用向上箭头键/向下键启动所选行(对象)上的点击功能?

1 个答案:

答案 0 :(得分:0)

好的,所以通过绑定到id来计算它,所以你按id获取元素并应用一个点击,首先设置一个id

<div id="{{i}}" *ngFor="let message of messages; let i=index" 
       (click)="addMessage(message); activeIndex = i"
      [ngClass]="{'message-list-active': activeIndex === i  }">
      {{message}}
 </div>

component.ts

if (event.code == "ArrowUp" && this.activeIndex > 0) {
    this.activeIndex--
     document.getElementById(this.activeIndex.toString()).click();
}
if (event.code == "ArrowDown" && this.activeIndex < this.messages.length - 1) {
    this.activeIndex++
     document.getElementById(this.activeIndex.toString()).click();
  }
}