Javascript angular2-如何选择动态创建的元素并聚焦它?

Javascript angular2-如何选择动态创建的元素并聚焦它?,javascript,html,angular,Javascript,Html,Angular,我有一个动态HTML元素列表,所有元素都有一个特定属性,例如“role=option” 我想选择第一个元素并给它焦点。在angular 1中,可以通过以下方式实现: angular.element(document.querySelector('[role="option"]')).focus() 在angular2中,我找不到做这件事的等效方法。所有答案似乎都涉及viewChild并为元素提供特定的ref,但HTML是通过*ngFor动态创建的,因此每个元素在循环中都会使用相同的ref 如何

我有一个动态HTML元素列表,所有元素都有一个特定属性,例如“role=option”

我想选择第一个元素并给它焦点。在angular 1中,可以通过以下方式实现:

angular.element(document.querySelector('[role="option"]')).focus()
在angular2中,我找不到做这件事的等效方法。所有答案似乎都涉及viewChild并为元素提供特定的ref,但HTML是通过*ngFor动态创建的,因此每个元素在循环中都会使用相同的ref


如何做到这一点?

您仍然可以使用模板引用变量并使用和属性来关注模板中的第一个元素。试试下面的方法

模板

控制器

从“@angular/core”导入{Component,TemplateRef,ViewChildren,QueryList,ElementRef}; @组成部分{ 选择器:“我的应用程序”, templateUrl:“./app.component.html”, 样式URL:['./app.component.css'] } 导出类AppComponent{ items=['item1','item2','item3','item4']; @ViewChildren'input'inputElems:QueryList; templateRefVariablevalue{ console.logvalue; } ngAfterViewInit{ this.inputElems.first.nativeElement.focus; } }
工作示例:

您仍然可以使用模板引用变量并使用和属性来关注模板中的第一个元素。试试下面的方法

模板

控制器

从“@angular/core”导入{Component,TemplateRef,ViewChildren,QueryList,ElementRef}; @组成部分{ 选择器:“我的应用程序”, templateUrl:“./app.component.html”, 样式URL:['./app.component.css'] } 导出类AppComponent{ items=['item1','item2','item3','item4']; @ViewChildren'input'inputElems:QueryList; templateRefVariablevalue{ console.logvalue; } ngAfterViewInit{ this.inputElems.first.nativeElement.focus; } } 工作示例: