Auto-focus Input and Open Keypad On View/ Page Load in Ionic 3 Application

Mobile applications having input fields for search or forms can be optimized in terms of user-friendliness if developer autofocus first input field or search field on application or page load. This behavior seems to be nominal and not of much importance but it really ads up to the convenience of the application user.

In Ionic application too we can achieve this behavior by 2 simple steps, the best thing is we don’t need any plugin for that. Using this method we can easily autofocus the input field and show keypad instantly so that the user is always ready to type in.

let’s implement this simple but important functionality in Ionic 3 Application

First, create a new Ionic 3 Application with a blank template

$ ionic start Ionic3InputFocusDemo blank

 

Now open home.html file then add a search input with search sign. In input tag we will add #searchInput, this will make this input dom element into a variable.

...
...
<ion-content padding>

  <ion-grid>
    <ion-row class="search-bar-wrap">
      <ion-col col-10>
          <ion-item>
            <ion-input type="text" #searchInput class="search-bar"></ion-input>
          </ion-item>
      </ion-col>
      <ion-col col-2>
        <ion-icon class="search-button" name="search"></ion-icon>
      </ion-col>
    </ion-row>
  </ion-grid>

</ion-content>

 

Next open home.ts file then add @ViewChild decorator to get an instance of the input variable in the component.

import { Component, ViewChild } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';


@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  @ViewChild('searchInput') sInput;

  constructor(
    public platform: Platform,
    public navCtrl: NavController
    ) {}

  ionViewDidLoad(){
    console.log("ionViewDidLoad");
    setTimeout(() => {
      this.sInput.setFocus();
    }, 500);
  }

}

Here we need to add this timeout of 800 milliseconds due to the time taken initialization of device resources available for application.

Leave a Comment

Your email address will not be published. Required fields are marked *