Setting focus on page load in Ionic

538 views Asked by At

I can't seem to get focus to set on page load. Here is what I'm trying to do right now:

INPUT:

<ion-input placeholder="SCAN LP TO ACKNOWLEDGE" type="number" [(ngModel)]="this.session.listService.licensePlate" required (keyup.enter)="ValidateAndAcknowledge()" #myInput ></ion-input>

TS FILE

export class AcknowledgePage {
  @ViewChild('input') myInput;

  constructor() {
      }

  ionViewDidLoad() {

    setTimeout(() => {
      console.log(this.myInput);
      this.myInput.setFocus();

    }, 150);

  }
}
2

There are 2 answers

0
Mohammed Iqbal khan On

I don't know why but @viewChild is not working for me at the end I used document.querySelector() in ionViewDidLoad() and set focus() and It's work for me.enter image description here

4
Sergey Rudenko On

So your ViewChild refers 'input' while your template states #myInput. You need to fix that:

export class AcknowledgePage {
  @ViewChild('myInput') myInput;

  constructor() {
      }

  ionViewDidLoad() {

    setTimeout(() => {
      console.log(this.myInput);
      this.myInput.setFocus();

    }, 150);

  }
}

Now even if this code will work for you on Android devices - this may not work on latest iOS (11.3+) since Apple actually wants users to trigger focus via explicit tap action and not programmatic-ally.