Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

typescript - How can I set focus to another input?

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

For example:

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

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.

UPDATE

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

For example

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 /> 

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 is the raw element, so you can use pure javascript on it.

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

I hope it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...