如何将离子搜索栏聚焦在按钮单击上 [英] How to focus ion-searchbar on button click

查看:110
本文介绍了如何将离子搜索栏聚焦在按钮单击上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将ion-searchbar集中在按钮单击上,但是它不起作用. 这是我的代码

I am trying to focus ion-searchbar on button click but it is not working. This is my code

打字稿

@ViewChild('search') search:ElementRef;

focusButton(){
       console.log(this.search);   //Searchbar {_config: Config, _elementRef: ElementRef, _renderer: RendererAdapter, _componentName: "searchbar", _mode: "md", …}
       console.log(this.search.nativeElement); //  null
       this.search.nativeElement.focus();      //  Cannot read property 'focus' of undefined
        this.search.nativeElement.setFocus();      // Cannot read property 'setFocus' of undefined

}

HTML

<ion-searchbar #search (ionCancel)="cancelSearch($event)" [showCancelButton]="true" [(ngModel)]="artists"></ion-searchbar>
        <ion-buttons end>
            <button [hidden]="showSearch" (click)="(showSearch = !showSearch) && focusButton()" ion-button icon-only>
              <ion-icon  name="search"></ion-icon>
            </button>
        </ion-buttons>

控制台输出在上面带代码的注释中.

The console output is above in comments with code.

推荐答案

希望您可以使用以下代码进行操作.只需使用setTimeout进行尝试,如下所示.

Hope you can do it using below code.Just try it using setTimeout as shown below.

.html

<ion-searchbar #search (ionCancel)="cancelSearch($event)" 
[showCancelButton]="true" [(ngModel)]="artists"></ion-searchbar>

<ion-buttons end>
   <button [hidden]="showSearch" (click)="(showSearch = !showSearch) && focusButton()" ion-button icon-only>
    <ion-icon  name="search"></ion-icon>
  </button>
</ion-buttons>

.ts

@ViewChild('search') search : any;

focusButton(): void {
    setTimeout(() => {
      this.search.setFocus();
    }, 500);
  }

这篇关于如何将离子搜索栏聚焦在按钮单击上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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