angular - 将焦点设置在 <input> 元素上

标签 angular angular5 angular-forms

我正在使用 Angular 5 开发前端应用程序,我需要隐藏一个搜索框,但单击按钮时,应该显示搜索框并聚焦。

我尝试了在 StackOverflow 上找到的一些带有指令等的方法,但无法成功。

这里是示例代码:

@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();
  }

搜索框未设置为焦点。

我怎样才能做到这一点?

最佳答案

编辑 2022 年:
通过@Cichy 的回答阅读更现代的方式 below

<小时/>

像这样修改显示搜索方法

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

关于angular - 将焦点设置在 &lt;input&gt; 元素上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59719182/

相关文章:

angular - 转换不适用于 angular5 动画

javascript - 在自定义下拉菜单 Angular 5 中使用箭头导航?

angular - ngSubmit.emit() 不会改变 formGroup 的提交属性

angular - 防止输入更改导致表单变脏(Angular 5.2)

html - 当输入的日期小于当前日期时,Angular 7 :Apply style sheet to input field on change of value i. e

javascript - VideoJS : Can't click on elements that are on top/overlay of the video

angular - Ngx Bootstrap 弹出框一次只显示一个弹出框

angular - 如何防止 Angular 加载组件两次?

javascript - Firebase 更新数据,但几秒钟后将其更改回原始值 "angularFire"

javascript - Angular 禁用按钮和垫输入错误消息