Ionic version:
[x] 4.x
Describe the Feature Request
Add support for autofocus
property to ionic core for feature parity with ion-input
. Previous patch for v3
in https://github.com/ionic-team/ionic/pull/8232 but probably outdated.
Describe Preferred Solution
Boolean property for ion-searchbar
will do.
<ion-searchbar autofocus></ion-searchbar>
Describe Alternatives
The alternative uses a simple timeout (don't follow this, not tested) based on angular.
<ion-seachbar #autofocus></ion-searchbar>
@Component(...)
export class SimpleSearch implements OnInit {
@ViewContent('#autofocus') searchbar;
ngOnInit() {
setTimeout(() => this.searchbar.focus(), 300);
}
}
Related Code
Additional Context
@ViewChild(IonSearchbar) myInput: IonSearchbar;
setTimeout(() => {
this.myInput.setFocus();
}, 150);
import { IonSearchbar} from '@ionic/angular';
Same deal with Vue, this works:
mounted() {
setTimeout(() => this.$refs.searchbar.setFocus(), 1)
}
Did anyone noticed that the alternative does not work in iOS since iOS 12.2? in 12.1 works fine but in 12.2 it does not work in safari or as app with cordova.
After calling .focus() nothing happens, but if I switch to another app and then back to the ionic app it focuses and the keyboard is shown.
Edit: I opened an issue #18054
Ionic version:
[x] 4.x
Angular version:
[x] 8.x
<ion-searchbar #autofocus></ion-searchbar>
import { Component, ViewChild } from '@angular/core';
import { IonSearchbar } from '@ionic/angular';
@ViewChild('autofocus', { static: false }) searchbar: IonSearchbar;
ngOnInit(){
setTimeout(() => this.searchbar.setFocus(), 500);
}
Without setTimeout
<ion-searchbar #searchbar></ion-searchbar>
@ViewChild('searchbar', { static: false }) searchbar: IonSearchbar;
ionViewDidEnter() {
this.searchbar.setFocus();
}
Like @zen09 said. I just add on.
ViewChild
query result completed in (ngAfterViewInit) AfterViewInit
.
From documentation: https://angular.io/api/core/ViewChild
View queries are set before the ngAfterViewInit callback is called.
So, can do like this.
ngAfterViewInit() {
if (this.baseSvc.isBrowser) { // OPTIONAL: this is my condition for my ng ssr
this.searchbar.setFocus();
}
}
I am still seeing this issue with angular 9 and ionic 5, the setFocus() method is not working within any stage of the lifecycle.
Most helpful comment
Ionic version:
[x] 4.x
Angular version:
[x] 8.x
<ion-searchbar #autofocus></ion-searchbar>
import { Component, ViewChild } from '@angular/core';
import { IonSearchbar } from '@ionic/angular';
@ViewChild('autofocus', { static: false }) searchbar: IonSearchbar;
ngOnInit(){ setTimeout(() => this.searchbar.setFocus(), 500); }