Ion-searchbar - Set Focus


#1

I’ve read Mike Hartington’s post on setting input focus: http://mhartington.io/post/setting-input-focus/

In that post you set a local variable (#input) and then use that variable in your code to set the focus. With the searchbar being generated how would I assign a local variable to it? In my case I have the searchbar hidden until a search button in the navbar is pressed, at that point I unhide the searchbar and would like to set focus and open the keyboard at the same time.


#2

Glad you enjoyed the post!

Currently the ion-searchbar does not have a method to set focus built it.
Something like this could be added though, would you be able to open an issue for it?


#3

I very much enjoyed the posts on your blog, very informative!

I have opened an issue as you suggested: https://github.com/driftyco/ionic/issues/5834

Thanks for your help Mike!


#4

As a workaround once ou have a reference to your searchbar you can do this:

this.mainSearchBar.inputElement.focus();


#6

I have done the following:

 import { Searchbar } from 'ionic-angular';

 export class MyComponent {

   @ViewChild('searchbar') searchbar:Searchbar;

    /* somew stuff here */
   ...
   anyMethodName() {
     this.searchbar.setFocus();
   } 
  
 }

.html

<ion-searchbar
#searchbar
>

it’s working now.


#7

In my case I have the searchbar hidden until a search button in the navbar is pressed

After using @chrisbenseler solution I had to add a timeout of about 50ms on the setFocus to get the DOM to load after un-hiding the searchbar element. Just FYI


#8

alsco77, I’ve tried it but it’s not working here.


#9

Natanael4354, try the following:

 @ViewChild(Searchbar) searchbar: Searchbar;

 ...
 ionViewDidEnter() {
      setTimeout(() => {
        this.searchbar.setFocus();
   });
 }

#10

yes it worked for me also and as a fresher i also learned how to select components from class (i.e. our .ts file) @chrisbenseler


#11

It worked for me thanks. Could you please explain why the setTimeout() is required here?


#12

Because @ViewChild(‘searchbar’) searchbar:Searchbar; considered after the loaded the this.searchbar.setFocus(). So wee need to timout to achieve this.


#13

i think’s , must use setInterval() for repeatedly blinking, setTimeout only once blinking


#14

Is there a better way to do this now in Ionic 3?

Worked for me using the below. Any less than 600 and it doesn’t work for me.
I’m not reloading the page so I don’t really understand why I need to do this. In a web app I can just keep the focus in an input and search on each keypress. This feels like a hack.

setTimeout(() => {
      this.searchbar.setFocus();
    }, 600);

#15

Ok I realised it was because I was using a LoadingController that I was losing focus on the SearchBar. I removed this and added a spinner to my list and problem resolved. No need to use setFocus in this case.