[Fixed] Ionic : Autofocus a text field

Issue

i know this question has been asked many times but i was unable to find my solution:

i am trying to atuofocus a text field on page load as below :

Html:

<input type="text" #autofocusfield>

TS File

Related import

import { Component,ViewChild } from '@angular/core';

Code to auto focus :

export class Tab1Page {
  @ViewChild('autofocusfield') inputtext; 

ionViewDidLoad() {         
    setTimeout(() => {
      this.inputtext.setFocus();
    }, 500);
  }

i also tried to use autofocus=’true’ but that did not work , Can someone please guide me how can i achieve this

Solution

this is all you need simply. demo in this stackblitz link

@ViewChild("autoFocus") private af: ElementRef;
constructor(public navCtrl: NavController) {}
ngAfterViewChecked() {
  this.af.nativeElement.focus();
}

You only need focus() method to set inside ngAfterViewChecked() hook.

Template of HTML is..

<input #autoFocus type="text" >

Leave a Reply

(*) Required, Your email will not be published