[英]angular2 - How to DOM select a dynamically created element and focus it?
I have a dynamic HTML list of elements, that all have a specific attribute (for example 'role=option').我有一个动态的 HTML 元素列表,它们都有一个特定的属性(例如'role=option')。
I want to select the first element and give it focus .我想 select 第一个元素并给它焦点。 In angular 1, it was possible through:
在 angular 1 中,可以通过:
angular.element(document.querySelector('[role="option"]')).focus()
In angular2, I can't find the equivalent way of doing this.在 angular2 中,我找不到等效的方法。 All answers seem to involve viewChild and giving a specific
#ref
to an element, but the HTML is created dynamically through *ngFor
, so every element would end up with the same #ref
in the loop.所有答案似乎都涉及 viewChild 并为元素提供特定的
#ref
,但 HTML 是通过*ngFor
动态创建的,因此每个元素最终都会在循环中使用相同的#ref
。
How to do this?这个怎么做?
You could still use the template reference variable and use ViewChildren
and the first
property to focus on the first element in the QueryList
.您仍然可以使用模板引用变量并使用
ViewChildren
和first
属性来关注QueryList
中的第一个元素。 Try the following尝试以下
Template模板
<ng-container *ngFor="let item of items; let i=index">
<input #input (change)="templateRefVariable(input.value)"/>
<br />
</ng-container>
Controller 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();
}
}
Working example: Stackblitz工作示例: Stackblitz
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.