Focus the ion-searchbar on ionViewDidEnter

The focus does not work. It said “Cannot read property ‘setFocus’ of undefined”. How can I fix it ?
ionViewDidEnter() {
setTimeout(()=>{
this.searchBar.setFocus();
}, 150);
}

Use this code to set focus on search bar.

import {Component, Input, ViewChild} from '@angular/core';
import {NavController} from 'ionic-angular';

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  @ViewChild('searchBar') myInput ;

  constructor(private navCtrl: NavController) { }

  ionViewDidLoad() {

    setTimeout(() => {
      this.myInput.setFocus();
    },150);

 }

}

and your search bar

<ion-searchbar
  [(ngModel)]="searchTerm"
  #searchBar
  [showCancelButton]="shouldShowCancel"
</ion-searchbar>

set #searchBar in ion-searchbar.

3 Likes

Thank @ravi_sojitra. It works properly now.

Glad to help you.
Accept the solution so that it can help others.

Thanks. :slight_smile:

@ravi_sojitra please take a look Change animation back button. Maybe you can help me again :slight_smile:

I dislike setTimeout() in general, and especially when used with magic numbers. It is a recipe for inconsistent behavior.

3 Likes

This does not work on android, the keyboard immediately disappear after popup.