angular – 如何在按钮单击时聚焦ion-searchbar

前端之家收集整理的这篇文章主要介绍了angular – 如何在按钮单击时聚焦ion-searchbar前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图在按钮点击上关注ion-searchbar,但它无法正常工作.
这是我的代码

打字稿

@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>

控制台输出位于带代码的注释中.

解决方法

希望你可以使用下面的代码来完成它.只需使用setTimeout尝试它,如下所示.

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

猜你在找的Angularjs相关文章