HTMLElement focus()阻止执行

时间:2018-01-11 09:25:32

标签: angular typescript event-handling

(以下代码是打字稿,我正在处理角度5,但我相信这不是罪魁祸首,但证明我错了!)

我有一个简单的输入,它将一些事件传递给角度组件

编辑:包含完整的组件代码)

<span class="__picker-container">
    <input type="text" #geoSearchBox (keypress)="keyPress($event)" (keyup)="searchTerms.next($event)" [placeholder]="placeholder" />
    <small *ngIf="isLoading">caricamento...</small>
    <div #pickerList class="__picker-list">
        <a href="javascript:;" *ngFor="let result of searchResults | async" (click)="select(result.id)">{{ result.name }} ({{ result.code }})</a>
    </div>
</span>

虽然keyup在输入的同级UL中通过休息显示结果执行简单搜索,但我使用keypress检查用户何时键入某些键盘代码被使用。

特别是我正在搜索keyDownkeyUp,以循环查看结果。看一下代码:

keyPress(event: KeyboardEvent) {
    const pl = <HTMLDivElement>this.pickerList.nativeElement;
    if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
        if (pl.childElementCount > 0) {
            if (event.key === 'ArrowDown') {
                this.childNodeIndex = this.childNodeIndex++ < pl.childElementCount - 1 ? this.childNodeIndex++ : 0;
            } else if (event.key === 'ArrowUp') {
                this.childNodeIndex = this.childNodeIndex - 1 >= 0 ? this.childNodeIndex - 1 : pl.childElementCount - 1;
            }

            console.log(this.childNodeIndex);
            (<HTMLElement>pl.children[this.childNodeIndex]).focus();
        }
    }
}

现在一切都很简单。

现在奇怪的行为:在调用focus()之后,它正确地聚焦html元素,但阻止执行:忽略其他按键事件。

如果我删除该行

(<HTMLElement>pl.children[this.childNodeIndex]).focus();

console.log为我发送的每次击键发出正确的值。

此代码有什么问题?

提前致谢 瓦莱里奥

1 个答案:

答案 0 :(得分:1)

如果您将焦点设置为https://abc.efgh.com/test?area=100&ref=5ERF2221" ,那么这是接收键盘事件的元素,而不是[{"status":"U","a":"","b":"","complete":"0000-00-00 00:00:00","link":"https://abc.efgh.com/test?area=100&ref=5ERF2221","count":0}]

将事件处理程序添加到<a href="...">也应该修复它

<input>