1

目前,我可以通过上下按箭头键来浏览列表中应用 css 类“message-list-active”的每条消息。当我点击行时,我触发点击功能并传递消息对象。但是当按箭头键时似乎无法触发单击元素,我尝试通过#fire 单击它,但它只单击第一个元素并且不允许我转到下一个列表。

应用程序.html

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

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

组件.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()
    }
   }

如何使用向上/向下箭头键在选定行(对象)上触发点击功能?

4

1 回答 1

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>

组件.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();
  }
}
于 2017-12-22T09:39:18.740 回答