Angularjs   发布时间:2022-04-20  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了angular5 – Angular 5设置焦点在输入元素上大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用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();
  }

搜索框未设置为焦点.
我怎样才能做到这一点?谢谢.

像这样修改show search方法
showSearch(){
  this.show = !this.show;  
  setTimeout(()=>{ // this will make the execution after the above Boolean has changed
    this.searcHelement.nativeElement.focus();
  },0);  
}

大佬总结

以上是大佬教程为你收集整理的angular5 – Angular 5设置焦点在输入元素上全部内容,希望文章能够帮你解决angular5 – Angular 5设置焦点在输入元素上所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。