How to focus ion-searchbar on button click

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

For those working with Angular 8 and Ionic 4 one can set the flag static: false which will consider that an *ngIf is involved and hiding the search bar for example. As soon *ngIf displays again the visual component (e.g. ion-searchbar)

@ViewChild('searchInput', {static: false}) searchInput: IonSearchbar;

  constructor() { }

  public setSearchbarVisible(isVisible) {
    this.isSearchbarOpened = isVisible;
    if (isVisible) {
      setTimeout(() => {
        this.searchInput.setFocus();
    }, 100);
    }
  }

Adding a type to the searchInput will also help with method and property insights, like setFocus(). That is neat code without daring to touch the wraped native elements.


  1. Add reference into the template

    <input #inputEl> or <ion-searchbar #inputEl> whatever you use as input

  2. Import ViewChild on the top of .ts and define a reference variable in component class

    import { ViewChild } from '@angular/core';
    @ViewChild('inputEl') inputElRef;
    
  3. Use nativeElement to access focus() function

    this.inputElRef.nativeElement.focus();