加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

angular5 – Angular 5设置焦点在输入元素上

发布时间:2020-12-17 09:28:05 所属栏目:安全 来源:网络整理
导读:我正在使用Angular 5进行前端应用程序,我需要隐藏一个搜索框,但点击一个按钮,搜索框将显示并设置焦点. 我已尝试使用指令左右的stackoverflow中找到的几种方法,但没有运气. 以下是示例代码: @Component({ selector: 'my-app',template: ` div h2Hello/h2 /di
我正在使用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);  
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读