如何将焦点设置为其他输入? [英] How can I set focus to another input?

查看:92
本文介绍了如何将焦点设置为其他输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当某些事件发生时,我需要能够将焦点切换到输入元素.如何在Angular 2中做到这一点?

I need to be able to switch focus to an input element when some event occurs. How do I do that in Angular 2?

例如:

<input (keyUp)="processKeyUp($event)"/>
<input (focusme)="alert('i am focused')"/>

在第一个输入键被按下时,我想聚焦第二个输入框.我想我需要使用自定义事件(代码段中的focusme),但是我不知道在何处或如何声明它,是否对其使用@Directive批注,或者不将其定义包含在组件中不知何故.简而言之,我很沮丧.

I want to focus the 2nd input box when a certain key is pressed in the first. I think I need to use a custom event (focusme in the snippet), but I don't know where or how to declare it, and whether to use a @Directive annotation for it, or include its definition in a component somehow. In short, I am stumped.

更新

忘了提及,我知道我可以通过使用html中的局部变量来做到这一点,但是我希望能够从组件中做到这一点,并且我希望能够在触发focusme时执行复杂的逻辑事件,以便控件监听它可以确定它是否适合他们. 谢谢!

Forgot to mention, I know I can do that by using local variables in the html, but I want to be able to do it from the component, and I want to be able to do complex logic when firing the focusme event so that controls listening to it can determine if it is meant for them or not. Thanks!

推荐答案

您只需将第二个输入作为变量传递给第一个输入即可

You can do this just passing the second input as a variable to the first one

例如

HTML

<!-- We pass focusable as a parameter to the processKeyUp function -->
<input (keyup)="processKeyUp($event, focusable)"/>

<!-- With #focusable we are creating a variable which references to the input -->
<input #focusable /> 

以后在您的js/ts中

Later in your js/ts

@Component({
  selector: 'plunker-app'
})
@View({
  templateUrl: 'main.html'
})
class PlunkerApp {

  constructor() {
  }

  processKeyUp(e, el) {
    if(e.keyCode == 65) { // press A
      el.focus();
    }
  }
}

el 是原始元素,因此您可以在其上使用纯JavaScript.

el is the raw element, so you can use pure javascript on it.

这是一个 plnkr ,因此您可以看到它正常工作.

Here's a plnkr so you can see it working.

希望对您有帮助.

这篇关于如何将焦点设置为其他输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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