Auto focus input field in ionic 5

I’m trying to auto focus input field in ionic 5. We had this exact same problem in previous version that we used ( ionic 3 ) that standard directives don’t work at all or don’t work properly … I found the autofocus directive for ion-input, but the problem is it works like 50% of the times, when it feels like it ( on the device ) … so my question: is there a proper solution to this ( now at least 4 year old ) problem, or do I need to write a hacky directive to this again? Is there a built in directive which will focus the default input ( and pop the keyboard up as it should ) reliably on all platforms?

Thanks!

2 Likes

it’s working all the time on iOS and Android devices.

autofocus="true"

Sorry but my experience differs. Here’s what I’m doing:

this is the code from the template with the ion-input that should be focused when user opens the page

            <ion-input
              [(ngModel)]="this.stepData.data.email"
              formControlName="email"
              type="email"
              placeholder="{{ 'email' | translate }}"
              autofocus="true"
            ></ion-input

I compile the app, make apk, install it on the device, kill the app ( if exists in the task manager ) then i start it and try to navigate to the page, and field should be auto focused - then i kill the app again, open it, navigate etc. I tried it , works only 20% of the times. So I’m glad it works for you, and that might give me a glimpse of hope. Does anyone have any idea what could cause it?

Thanks!

4 Likes

Hello i’m Using angular. you can also implement this method with other framework.
you can try this:
IonViewDidEnter() function will trigger after content is fully transitioned.

for more info: Angular Page Component Life Cycle - App Events Documentation

in your component.html

    <ion-item *ngIf="isContentLoaded" >
      <ion-label position="stacked">How much your Resin you have right now?</ion-label>
      <ion-input [autofocus]="true" (ionChange)="getResinValue($event)" inputmode="decimal"></ion-input>
    </ion-item>

In your component.ts

...
  isContentLoaded: boolean = false;
...

  ionViewDidEnter() {
    this.isContentLoaded = true;
  }