我正在构建Angular4应用程序。我的工作与良好的用户体验和导航之间的表单字段只使用键盘。我有这样的问题,当用户按下Tab键并到达这个+标志(图1)时,按下Enter键,然后这个按钮移动到下一行(图2),焦点就消失了。问题是如何处理这个Enter键以将焦点移到下一行,并将selector焦点放在该行上(缺省情况下使用Merchant URL值)。
现在,当用户在+上按Enter时,模板中的这个按钮会因为*ngIf而消失,并且会生成新的行。有什么建议吗?怎样才能获得更好的键盘用户体验?如何将焦点从消失的+更改为下一行组件,该组件已不可见,但在处理Enter结束时它将可见。
图1。

图2。

解决方案
import { DOCUMENT } from '@angular/common';
import { Component, Inject, AfterViewChecked } from '@angular/core';
constructor(
@Inject(DOCUMENT) private _document: Document
) { // bla bla bla }因为我在模板中控制我生成的元素id,所以我可以存储我想要在处理Enter键时关注的元素的id,并且我需要实现AfterViewChecked。
onEnter() {
this.focusOn = 'my-generated-element-id';
// put new model data to the array so template can generate new row
}
// this method is called very frequently so I only need to set focus
// when I need it and then clear focusOn variable.
ngAfterViewChecked(): void {
if (this.focusOn) {
let element = this._document.getElementById(this.focusOn);
if (element) {
element.focus();
this.focusOn = null;
}
}
}发布于 2018-05-14 22:49:28
您可以使用ViewChildren来跟踪input或任何元素。然后订阅QueryList中的更改。在这里,您可以专注于添加的最后一个实例。
这是一个minimal example in stackblitz
import { Component, ViewChildren, QueryList, AfterViewInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit{
name = 'Angular 6';
items = ['Item1', 'item2'];
@ViewChildren('input') inputs: QueryList<any>;
ngAfterViewInit() {
this.inputs.changes.subscribe(changes => {
changes.last.nativeElement.focus();
})
}
addItem() {
this.items.push(`Item${this.items.length + 1}`)
}
}<hello name="{{ name }}"></hello>
<div *ngFor="let item of items">
<input #input [placeholder]="item"/>
</div>
<button type="button" (click)="addItem()">Add Item</button>这是如果您想要关注添加的新行中的输入。要将焦点保持在+按钮上,您可以使用ViewChild。如果这不是你想要的,试着在Stackblitz中创建一个最小的例子。
https://stackoverflow.com/questions/50331837
复制相似问题