Setting Focus to an Input in Ionic

Have you tried a using it in ionViewDidEnter lifecycle hook instead of ionViewDidLoad - works for me

I find if I put it in a ionViewDidLoad the keyboard disappears and UX is broken,

what Iā€™ve found works (on device) is to put the a ionViewDidEnter lifecycle hook

ionViewDidEnter()
  {
    setTimeout(() => {
      this.inputToFocus.setFocus();
    },200)
  }  

I had this problem too until I used the ionViewDidEnter lifecycle hook

ionViewDidEnter()
  {
    setTimeout(() => {
      this.inputToFocus.setFocus();
    },200)
  }  
2 Likes

Use index for generating IDs

*ngFor=ā€œlet phoneInput of phoneInputList; let i = indexā€

when you have unique id for input create function:

setTimeout(() => {
const inputFieldIDElement = document.getElementById(ā€œInputFieldIDā€ + index);
if (inputFieldIDElement) {
const inputTagCollection = inputFieldIDElement.getElementsByTagName(ā€œinputā€);
if (inputTagCollection && inputTagCollection.item(0)) {
const inputElement = inputTagCollection.item(0);
inputElement.focus();
}
}
}, 300);

1 Like

I think this will be helpful

  1. Add reference into the template
    <input #inputEl>

  2. Import ViewChild on the top of .ts and define a reference variable in class

     import { ViewChild } from '@angular/core';
      ...
     @ViewChild('inputEl') inputElRef;
    
  3. Use nativeElement to access focus() function
    this.inputElRef.nativeElement.focus();

2 Likes

Use ngAfterViewChecked() Angular hook and execute .setFocus() inside it.

While working with the Ionic 3 Framework I came across (as it turns out) popular problem of autofocusing an input after showing a component on the page.

The most popular answer to this problem advises to use setTimeout

ionViewLoaded() {
    setTimeout(() => {
        this.myInput.setFocus();
    },150);
}

I hate such workarounds so Iā€™ve decided to dig deeper. While none of the available Ionic lifecycle hooks works, in that case, there are also Angular lifecycle hooks. It turns out that ngAfterViewChecked is the one I was looking for:

ngAfterViewChecked() {
    this.myInput.setFocus()
}

So that is clean setFocus() solution for Ionic without using setTimeout() workaround.

refer to the input element with this.myInput you have to define it inside your Component as a ViewChild.

Here is the example of Modal Component which will autofocus its input after showing itself on the page.
Javascript:

@Component({
  selector: 'my-modal',
  templateUrl: 'my-modal.html',
})
export class MyModal {

  @ViewChild('myInput') myInput;

  constructor( ) { }

  ngAfterViewChecked() {
    this.myInput.setFocus()
  }

  dismiss() {
    this.viewCtrl.dismiss();
  }
}

If you need to set focus on an input at init component, set the class input-has-focus by default to ion-item just like this:

<ion-item class="input-has-focus">

Thatā€™s all!

1 Like

what are the properties inside the ā€œinput-has-focusā€ class.

Hi! I tried this solution and it works fine: the input focuses when the component is loaded, but then the keyboard cannot be closed afterwards. Whenever I try to hide it, it pops up again. Is there a way of solving this?

I tried ngAfterViewInit() insead of ngAfterViewChecked(), because this way it should be called only once. But in this case, when the component loads, the input is focused (and keyboard appears) only for a second, then keyboard closes back again and the field is no longer focused. I donĀ“t know why, seems like something else is resetting the setFocus command.

Any ideas?

Funciona correctamente en Ionic 4.

its working for me sirā€¦thanks

1 Like

I had a lot of problems with this issue as well and discovered this one:

  @ViewChild('elementName') viewChildElement;

ngAfterViewChecked() {
    //check if present on page since this is called a lot
    if(document.body.contains(document.getElementById('elementid'))){
      this.viewChildElement.setFocus();
    }
  }

This combines a mix of things because the ngAfterViewInitChecked is called very often, and on my page I have conditional html statements so the input field is not always displayed.
Also, when this specific element is displayed, this is the only element on the screen, if you have more than one it will constantly change focus back to this one.

To those who recently saw that autofocus stopped working on IOS devices, I have the solution.
After trying to find the answer on the web I decided to go and check plugin repositories for releases.

Suddenly I found out hat the problem is related to web view plugin and this 12.01 update for ios platform.
So to fix it in your projects you need to update a plugin for the version, containing a specific fix. I did that and it worked for me.

ionic cordova plugin rm cordova-plugin-ionic-webview --force
ionic cordova plugin add cordova-plugin-ionic-webview@2.4.1

Here is the link in repo about the commit https://github.com/ionic-team/cordova-plugin-ionic-webview/releases/tag/v2.4.1

I hope it helps someone.

1 Like

This works nice but instead get the reference through the html, i added it via viewchild. The thing is why do you use itemTop - 80? whereā€™s that 80 from? or it just comes with try and error to adjust the view?

Thanks man ā€¦ its working!

$ ionic info
Ionic:

Ionic CLI : 5.4.6 (/home/gabriel/workspace/node_modules/ionic)
Ionic Framework : ionic-angular 3.9.2
@ionic/app-scripts : 3.2.0

Cordova:

Cordova CLI : 9.0.0 (cordova-lib@9.0.1)
Cordova Platforms : android 6.4.0
Cordova Plugins : cordova-plugin-ionic-webview 1.2.1, (and 16 other plugins)

Utility:

cordova-res : 0.8.1
native-run : 0.2.9

System:

NodeJS : v8.16.2 (/home/gabriel/.nvm/versions/node/v8.16.2/bin/node)
npm : 6.13.1
OS : Linux 4.15

This actually worked fo me.
I was trying it for OTP Verification

<ion-input #Field1 (ionInput)=nextf(Field2)>
<ion-input #Field2 (ionInput)=nextf(Field3)>
<ion-input #Field3 (ionInput)=chick()>

.ts --------------------------------------------------

nextf(x: any){
x.setFocus();
}