角度2/4将焦点放在输入元素上 [英] Angular 2/4 set focus on input element

查看:45
本文介绍了角度2/4将焦点放在输入元素上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过(单击)事件将焦点设置在输入上?我已经安装了此功能,但是我显然错过了一些东西(这里是新手)

How can I set focus on an input by (click) event? I have this function in place but I'm clearly missing something (angular newbie here)

sTbState: string = 'invisible';
private element: ElementRef;
toggleSt() {
  this.sTbState = (this.sTbState === 'invisible' ? 'visible' : 'invisible');
  if (this.sTbState === 'visible') {
    (this.element.nativeElement).find('#mobileSearch').focus();
  }
}

推荐答案

您可以为此使用@ViewChild装饰器.文档位于 https://angular.io/api/core/ViewChild .

You can use the @ViewChild decorator for this. Documentation is at https://angular.io/api/core/ViewChild.

这是工作正常的plnkr: http://plnkr.co/edit/KvUmkuVBVbtL1AxFvU3F

Here's a working plnkr: http://plnkr.co/edit/KvUmkuVBVbtL1AxFvU3F

此代码要点归结为,为您的输入元素命名,并在模板中关联一个click事件.

This gist of the code comes down to, giving a name to your input element and wiring up a click event in your template.

 <input #myInput />
 <button (click)="focusInput()">Click</button>

在组件中,实现@ViewChild@ViewChildren来搜索元素,然后实现点击处理程序以执行所需的功能.

In your component, implement @ViewChild or @ViewChildren to search for the element(s), then implement the click handler to perform the function you need.

export class App implements AfterViewInit {
  @ViewChild("myInput") inputEl: ElementRef;

  focusInput() {
    this.inputEl.nativeElement.focus()
  }

现在,单击按钮,然后闪烁的插入符号将出现在输入字段内.不建议使用ElementRef作为安全隐患, 例如XSS攻击( https://angular.io/api/core/ElementRef ),因为导致组件的便携性降低.

Now, click on the button and then the blinking caret will appear inside the input field. Use of ElementRef is not recommended as a security risk, like XSS attacks (https://angular.io/api/core/ElementRef) and because it results in less-portable components.

还要注意,当ngAfterViewInit事件触发时,inputEl变量将首先可用.

Also beware that, the inputEl variable will be first available, when ngAfterViewInit event fires.

这篇关于角度2/4将焦点放在输入元素上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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