Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic v4 - how do I autofocus on a Input?

I have a view with an input <ion-input #codigobarras></ion-input>

How can I auto focus on this input?

What have I tried

@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 -->
like image 679
SpaceDogCS Avatar asked Feb 27 '19 20:02

SpaceDogCS


People also ask

How do you autofocus input field in ionic?

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.

How do I autofocus input field in bootstrap?

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.

Does autofocus attribute always set focus on first input field in HTML5?

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.


3 Answers

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.

like image 183
Aymer-El Avatar answered Sep 21 '22 11:09

Aymer-El


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();
}
like image 21
Juan Antonio Avatar answered Sep 19 '22 11:09

Juan Antonio


This should work

<ion-input autofocus="true"></ion-input>
like image 36
ppichier Avatar answered Sep 20 '22 11:09

ppichier