我有一个动态 HTML 元素列表,所有元素都有特定的属性(例如“role=option”)。
我想选择第一个元素并为其提供焦点。在 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
关于javascript - angular2 - 如何 DOM 选择动态创建的元素并聚焦它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62158025/