Angular 4 在通过键盘箭头选择的元素上触发点击事件
Angular 4 fire click event on element selected through keyboard arrows
目前,我可以通过按上下箭头键应用 css class "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()
}
}
如何使用向下箭头键 up/key 在选定的行(对象)上触发点击功能?
好的,所以通过绑定到 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();
}
}
目前,我可以通过按上下箭头键应用 css class "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()
}
}
如何使用向下箭头键 up/key 在选定的行(对象)上触发点击功能?
好的,所以通过绑定到 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();
}
}