2017-10-13 82 views
4

我是Angular的新手,并且试图用它来设置ID为“input1”的输入焦点。我使用下面的代码:如何使用Angular4通过元素ID设置焦点

@ViewChild('input1') inputEl: ElementRef; 

然后在组件后:

this.inputEl.nativeElement.focus(); 

但它无法正常工作。我究竟做错了什么?任何帮助都感激不尽。

+0

https://stackoverflow.com/questions/38307060/how-to-set-focus-on-element-with-binding –

+0

输入是动态生成的PrimeNg模板的一部分。我使用jquery在元素上设置id,但我不知道如何设置[focus]。有另一种方法吗? –

+0

谢谢@Z.Bagley!你提到的问题中的答案之一就是解决方案。 –

回答

1

一个由@ Z.Bagley中提到的问题的答案给了我答案。我必须从@ angular/core将Renderer2导入到我的组件中。然后:

const element = this.renderer.selectRootElement('#input1'); 

setTimeout(() => element.focus(), 0); 

谢谢@MrBlaise的解决方案!

7

组件

import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core'; 
... 

@ViewChild('input1') inputEl:ElementRef; 

ngAfterViewInit() { 
     this.inputEl.nativeElement.focus(); 
} 

HTML

<input type="text" #input1> 
+0

如果组件的id是动态生成的,该怎么办? –

+0

你的意思是输入的id?我认为这不是可能的。 –

相关问题