I have a view with an input <ion-input #codigobarras></ion-input>
How can I auto focus on this input?
@ViewChild('codigobarras') input_codigobarras: Input;
...
ionViewDidEnter() {
this.input_codigobarras.focus(); // didn't work = temp2.focus is not a function
this.input_codigobarras.focus.emit(); // didn't work = do nothing, just returns undefined
this.input_codigobarras.getElementRef().nativeElement.focus() // didn't work = do nothing, just returns undefined
this.input_codigobarras.setFocus(); // didn't work = do nothing, just returns undefined
}
<ion-input [autofocus]></ion-input> <!-- Didn't work -->
Insert <ion-input autofocus="true"></ion-input> to your HTML page. Execute ionic serve in Ionic CLI. Wait for browser to pop up with app and observe behavior.
Answer: Use the jQuery . focus() method You can simply use the jQuery . focus() method to set the focus on the first input box or textarea inside the Bootstrap modal when it is loaded upon activation.
The first input or textarea in source order that has the autofocus attribute will be focused on page load. In browsers without autofocus support, no fields will be focused on page load, unless otherwise given focus with JavaScript.
I had an conflict of focus regarding with ion-input inside a ion-modal. In fact, after using a timeout, i realized that my ion-input was focus and unfocused instantly.
setTimeout(() => this.ionInput.setFocus(), 100);
So, I console log the activeElement (the one that is focused) with:
document.activeElement
And the console output ion-modal.
Hence, I had to wait the ion-modal to be "fully loaded" to use the setFocus with as mentioned above.
A more generic solution to do this when and where you want could be:
<ion-input ... #inputId></ion-input>
So with a ViewChild
in your controller you can easily set the focus on:
@ViewChild('inputId', {static: false}) ionInput: { setFocus: () => void; };
...
setFocusOnInput() {
this.ionInput.setFocus();
}
This should work
<ion-input autofocus="true"></ion-input>
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