如何使用Angular4通过元素ID设置焦点 [英] How to use Angular4 to set focus by element id
本文介绍了如何使用Angular4通过元素ID设置焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是Angular的新手,正在尝试使用它来设置ID为"input1"的输入的焦点.我正在使用以下代码:
I am new to Angular, and am trying to use it to set focus on an input with the id "input1". I am using the following code:
@ViewChild('input1') inputEl: ElementRef;
然后在该组件的后面:
this.inputEl.nativeElement.focus();
但是它不起作用.我究竟做错了什么?任何帮助将不胜感激.
But it isn't working. What am I doing wrong? Any help will be much appreciated.
推荐答案
@ Z.Bagley提到的问题中的一个答案给了我答案.我必须将Renderer2从@ angular/core导入到我的组件中.然后:
One of the answers in the question referred to by @Z.Bagley gave me the answer. I had to import Renderer2 from @angular/core into my component. Then:
const element = this.renderer.selectRootElement('#input1');
// setTimeout(() => element.focus, 0);
setTimeout(() => element.focus(), 0);
感谢@MrBlaise解决方案!
Thank you @MrBlaise for the solution!
这篇关于如何使用Angular4通过元素ID设置焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文