I need to set focus and open keyboard after page loads or modal with input is shown.
Simple .focus() works in Android and also in iPad in landscape mode. However in portrait mode and on iPhone focus is set but keyboard not shown.
I tried also solution with adding and focusing on additional element, but it doesn't work with Angular. (IOS show keyboard on input focus)
@ViewChild('searchBarInput') searchBarInput: ElementRef;
ngAfterViewInit(): void {
setTimeout(()=> {
this.searchBarInput.nativeElement.focus();
this.searchBarInput.nativeElement.click();
},180);
}
test application: https://inputfocus.vercel.app/
expectation is that after page is loaded and focus set, user can start typing. It is simplified version - I need this on modal, but behaviour on iOS is similar
I think I found the solution. on iOS (iphone) and iPad portrait mode, focus() needs to be triggered by user action. So we need to set this immediately after use clicks button showing modal or new div with target input field.
We can create this new field automatically, set focus, and remove it after moving focus to target field.
On button click we need to create temporary input, append to existing container (close to our input) and focus on it.
btnClicked() {
this.showModal = true;
this.searchBar = this.renderer2.selectRootElement('#searchBar', true);
// 2nd argument preserves existing content
// setting helper field and focusing on it
this.inputHelper = this.renderer2.createElement('input');
this.renderer2.appendChild(this.searchBar, this.inputHelper);
this.inputHelper.focus();
let event = new KeyboardEvent('touchstart',{'bubbles':true});
this.searchBarButton.nativeElement.dispatchEvent(event);
}
after modal/target input is shown, we move focus and remove temporary one:
initiateKeyboard() {
setTimeout(()=> {
this.searchBarInput.nativeElement.focus();
this.renderer2.removeChild(this.searchBar, this.inputHelper);
},180);
}
and template:
<div id="searchBar">
<input type="button" class="button is-link is-light" value="Search" (click)="btnClicked()" (touchstart)="initiateKeyboard()" #searchBarButton>
</div>
You just need to remember that iPhone may zoom screen, so you need to adjust parameters of temporary input.
working solution: https://inputfocus.vercel.app/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With