【发布时间】:2021-07-31 08:21:05
【问题描述】:
我写了一个表格,其中都包含输入字段。对于这个模板,我开发了一个 keyCode 导航。可以向上、向下、向左和向右导航。我必须在代码中添加什么才能使光标直接聚焦在导航时?
我的代码:
// Snippet from HTML
...
<tbody formArrayName="rows">
<tr *ngFor="let rowControl of rows.controls; let rowIndex = index">
<td [formGroupName]="rowIndex" appArrowKeyNav *ngFor="let column of displayedColumns; let columnIndex = index;">
<div>
<span>
<label>
<input [formControl]="rowControl.get(column.attribute)">
</label>
</span>
</div>
</td>
</tr>
</tbody>
// TS
public move(object: any) {
const inputToArray = this.inputs.toArray();
const cols = this.displayedColumns.length;
let index = inputToArray.findIndex((x) => x.element === object.element);
// console.log('Index found:', index);
switch (object.action) {
case 'UP':
index -= cols;
break;
case 'DOWN':
index += cols;
break;
case 'LEFT':
index -= 1;
break;
case 'RIGHT':
index += 1;
break;
}
if (index >= 0 && index < this.inputs.length) {
console.log('Navigating to index:', index);
inputToArray[index].element.nativeElement.focus();
}
}
// Directive
@HostListener('keydown', ['$event']) onKeyUp(event: KeyboardEvent) {
switch (event.key) {
case 'ArrowUp':
this.keyboardService.sendMessage({ element: this.element, action: 'UP' });
break;
case 'ArrowLeft':
this.keyboardService.sendMessage({ element: this.element, action: 'LEFT' });
break;
case 'ArrowDown':
this.keyboardService.sendMessage({ element: this.element, action: 'DOWN' });
break;
case 'ArrowRight':
this.keyboardService.sendMessage({ element: this.element, action: 'RIGHT' });
break;
case 'Enter':
this.keyboardService.sendMessage({ element: this.element, action: 'ENTER' });
break;
}
}
这里是我的Stackblitz:https://stackblitz.com/edit/angular-wmfjhh-zfkyyx?file=app%2Ftable-basic-example.html
【问题讨论】:
-
您显示的代码有什么问题?哪里失败了?
-
我已经尝试实现,不幸的是不起作用。我已经在 Stackblitz 中实现了我的代码。不幸的是,该表不适用于我的指令......你能告诉我我做错了什么吗?我的工作:stackblitz.com/edit/…
-
什么意思
does not work你期待什么。什么失败了?`请尽可能清楚。假设我们什么都不知道——因为……我们知道! -
with 不起作用我的意思是当我单击输入字段然后尝试使用箭头键导航时,我的表中的指令没有反应。我已经实现了一切,不知道为什么它不起作用。
-
你能看看我的stackblitz吗?也许你能找到错误。
标签: javascript angular typescript keycode