如何将重点放在具有绑定的元素上? [英] How to set focus on element with binding?

查看:95
本文介绍了如何将重点放在具有绑定的元素上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Angular2中,如何设置元素焦点上的绑定. 我不想使用elementRef进行设置. 我认为在AngularJS中有ngFocus指令 在Angular2中没有这样的指令

In Angular2 how can I set binding on element focus. I don't want to set it with elementRef. I think in AngularJS there is ngFocus directive In Angular2 there is no such directive

推荐答案

渲染器服务现已已弃用(从Angular 4.x开始) 新的Renderer2服务没有invokeElementMethod. 您可以做的就是获得对这样的元素的引用:

Renderer service is now deprecated (as of Angular 4.x) The new Renderer2 service doesn't have the invokeElementMethod. What you can do is to get a reference to the element like this:

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

然后您可以使用它来专注于该元素,如下所示:

And then you can use that to focus on that element like so:

element.focus();

selectRootElement工作原理的更多信息此处:

More on how selectRootElement works here:

如果该元素没有被聚焦,则常见的问题是该元素尚未准备就绪. (例如:禁用,隐藏等).您可以这样做:

If the element doesn't get focused the common issue is that the element is not ready. (eg.: disabled, hidden etc.). You can do this:

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

这将创建一个宏任务,该宏任务将在下一个VM回合中运行,因此,如果启用了该元素,焦点将正常运行.

This will create a macrotask that will run in the next VM turn, so if you enabled the element the focus will run properly.

这篇关于如何将重点放在具有绑定的元素上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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