shah shah - 1 month ago 18
TypeScript Question

How to focus ion-searchbar on button click

I am trying to focus

ion-searchbar
on button click but it is not working.
This is my code

Typescript

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

Answer Source

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