如何专注于某个领域? [英] How to focus on a field?

查看:261
本文介绍了如何专注于某个领域?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Angular 2更新到Angular 4,并且在文档中编写为使用Renderer2而不是已弃用的Renderer.

I updated from Angular 2 to Angular 4 and in the docs it's written to use the Renderer2 instead of Renderer which is deprecated.

现在正在查看渲染器,但是找不到像我以前那样调用focus()方法的方法.

Now am looking into the Renderer source, but cannot find a way to invoke the focus() method as I used to.

旧方法:

this.renderer.invokeElementMethod(element, 'focus', []);

什么是新的方式?

编辑

如果我要关注的元素是通过QuerySelector获得的,怎么办?

What if the element i am focusing onto is obtained via QuerySelector?

例如:

let inputField = document.querySelectorAll('.dialog input');
if ( inputField[0] ) {
   inputField[0].focus();
}

由于它是通过QuerySelector获得的,因此focus()方法不存在.

Since its obtained via QuerySelector, the focus() method doesn't exist on it.

推荐答案

已弃用invokeElementMethod,并且找不到返回到新渲染器的方式.要将焦点设置为元素,您现在可以简单地使用它:

The invokeElementMethod is deprecated, and will not find its way back into the new renderer. To set focus to an element, you can simply use this now:

element.nativeElement.focus();

如果使用的是document.querySelectorAll,则说明您执行的不是角度方法,您应该找到另一种方法.如果没有其他方法可以使用,则适用相同的原则. focus()方法是普通的javascript,因此您可以在angular2/typescript中使用它.不过,请确保在组件的ngAfterViewInit挂钩内执行querySelectorAll:

If you are using document.querySelectorAll, you are doing something not the angular way, and you should find another way to do it. If there is no other way to do it, then the same principle applies. The focus() method is plain javascript, so you can use it within angular2/typescript. Be sure to do the querySelectorAll inside the ngAfterViewInit hook of the component though:

ngAfterViewInit() {
   let inputField: HTMLElement = <HTMLElement>document.querySelectorAll('.dialog input')[0];
   inputField && inputField.focus();
}

这篇关于如何专注于某个领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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