Hi everyone.
I cannot find any information about how to autofocus an ion-searchbar (ionic 2)
I am using beta 7. I have tried an autofocus attribute which does not work.
Has anyone got the answer?
My implementation is simply <ion-searchbar></ion-searchbar>
1 Like
There is not autofocus ability for ion-searchbar.
Have looked into it quite a bit, we decided that autofocus was too problematic.
Working across different devices/browsers, they all handle autofocus a bit differently.
This causes a lot of problems so we decided not to support it.
2 Likes
Thanks for your reply - understood. If anyone knows of a workaround for this please post
I wanted to do the same thing when a modal gets opened by the user. Here is my quick solution:
I’m adding a “unique” class to the search bar and call .focus()
on the input element inside it during ionViewDidEnter()
.
<ion-searchbar class="my-page-name-searchbar"></ion-searchbar>
ionViewDidEnter() {
let elem = document.querySelector('.the-page-name-searchbar input');
if (elem) {
elem.focus();
}
}
You can extend the code inside ionViewDidEnter()
to open the keyboard by using the Cordova plugin with the following code:
// add this import
import { Keyboard } from 'ionic-native';
Keyboard.show();
But be aware that Keyboard.show();
doesn’t work on iOS.
Hope that helps .
2 Likes
below code actually is not compilable using typescript, Ts is complaining that elem has no method ‘focus’. any idea?
Just cast the Element
to HTMLInputElement
.
This should work:
let elem = <HTMLInputElement>document.querySelector('.some-class input');
if (elem) {
elem.focus();
}
By the way, it’s possible to get it working on iOS too (you need to switch a flag in /config.xml
), but then you have to care about keyboard hiding yourself, that might be challenging.
i found much cleaner solution
@ViewChild('mainSearchbar') searchBar: Searchbar;
...
ionViewDidEnter() {
setTimeout(() => {
this.searchBar.setFocus();
}, 150);
}
8 Likes
use jquery to set focus !!!
setTimeout(function () {
$('.searchbar-input').focus();
}, 500);
- import searchabar
import {
Searchbar
} from 'ionic-angular';
add in class
@ViewChild(Searchbar) searchbar:Searchbar;
ionViewDidEnter(){
setTimeout(() => {
this.searchbar.setFocus();
}, 0);
}