将焦点设置在 <input>元素 [英] Set focus on <input> element

查看:40
本文介绍了将焦点设置在 <input>元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Angular 5 处理前端应用程序,我需要隐藏一个搜索框,但单击按钮后,搜索框应该会显示并聚焦.

我已经尝试了在 StackOverflow 上找到的一些带有指令的方法,但都没有成功.

这是示例代码:

@Component({选择器:'我的应用',模板:`<div><h2>你好</h2>

<button(点击)="showSearch()">显示搜索</button><p></p><表格><div ><input *ngIf="show" #search type="text"/>

</表单>`,})导出类 App 实现 AfterViewInit {@ViewChild('search') searchElement: ElementRef;显示:假;名称:字符串;构造函数(){}显示搜索(){this.show = !this.show;this.searchElement.nativeElement.focus();警报(焦点");}ngAfterViewInit() {this.firstNameElement.nativeElement.focus();}

搜索框未设置为焦点.

我该怎么做?

解决方案

修改show search方法如下

showSearch(){this.show = !this.show;setTimeout(()=>{//这将在上述布尔值改变后执行this.searchElement.nativeElement.focus();},0);}

I am working a front-end application with Angular 5, and I need to have a search box hidden, but on click of a button, the search box should be displayed and focused.

I have tried a few ways found on StackOverflow with directive or so, but can't succeed.

Here is the sample code:

@Component({
   selector: 'my-app',
   template: `
    <div>
    <h2>Hello</h2>
    </div>
    <button (click) ="showSearch()">Show Search</button>
    <p></p>
    <form>
      <div >
        <input *ngIf="show" #search type="text"  />            
      </div>
    </form>
    `,
  })
  export class App implements AfterViewInit {
  @ViewChild('search') searchElement: ElementRef;

  show: false;
  name:string;
  constructor() {    
  }

  showSearch(){
    this.show = !this.show;    
    this.searchElement.nativeElement.focus();
    alert("focus");
  }

  ngAfterViewInit() {
    this.firstNameElement.nativeElement.focus();
  }

The search box is not set to focus.

How can I do that?

解决方案

Modify the show search method like this

showSearch(){
  this.show = !this.show;  
  setTimeout(()=>{ // this will make the execution after the above boolean has changed
    this.searchElement.nativeElement.focus();
  },0);  
}

这篇关于将焦点设置在 &lt;input&gt;元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆