如何使用 Angular4 通过元素 id 设置焦点 [英] How to use Angular4 to set focus by element id

查看:29
本文介绍了如何使用 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);

感谢@MrBlaise 的解决方案!

Thank you @MrBlaise for the solution!

这篇关于如何使用 Angular4 通过元素 id 设置焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆