![](/img/trans.png)
[英]How to move focus to next element on enter on dynamically created select
[英]angular2 - How to DOM select a dynamically created element and focus it?
我有一个动态的 HTML 元素列表,它们都有一个特定的属性(例如'role=option')。
我想 select 第一个元素并给它焦点。 在 angular 1 中,可以通过:
angular.element(document.querySelector('[role="option"]')).focus()
在 angular2 中,我找不到等效的方法。 所有答案似乎都涉及 viewChild 并为元素提供特定的#ref
,但 HTML 是通过*ngFor
动态创建的,因此每个元素最终都会在循环中使用相同的#ref
。
这个怎么做?
您仍然可以使用模板引用变量并使用ViewChildren
和first
属性来关注QueryList
中的第一个元素。 尝试以下
模板
<ng-container *ngFor="let item of items; let i=index">
<input #input (change)="templateRefVariable(input.value)"/>
<br />
</ng-container>
Controller
import { Component, TemplateRef, ViewChildren, QueryList, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
items = ['item1', 'item2', 'item3', 'item4'];
@ViewChildren('input') inputElems: QueryList<ElementRef>;
templateRefVariable(value) {
console.log(value);
}
ngAfterViewInit() {
this.inputElems.first.nativeElement.focus();
}
}
工作示例: Stackblitz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.