How to add and set ionic autofocus input

In ionic 5 autofocus of an HTML5 attribute that doesn’t work consistently across different platforms. In this quick post, I will walk you through how to add and set ionic autofocus input in an Ionic 5 Angular application.

When working with the Angular component, we often use @ViewChild decorator and template reference to get access to a specific element instance in a component typescript.  In your template add ion-searchbar tag or any input tag with #autofocus as a local variable, this variable can be used in our typescript component file to add autofocus after 300 milliseconds. Ionic have Searchbar component, we should be used ion-searchbar component instead of input to search lists.

To create and run an Ionic project, We need Node js and Ionic CLI already install in our system, if not then check how to install Node js and Ionic in Ubuntu. Ionic CLI allows us to create an Ionic project, generate application and library code, and perform a variety of ongoing development tasks such as testing, bundling, and deployment. To install the Ionic CLI, open a terminal, and run the following command:

npm install -g @ionic/cli

Ionic autofocus example

ionic autofocus input
<ion-header [translucent]="true">
      Ionic autofocus

<ion-content [fullscreen]="true">
  <ion-searchbar color="danger" #autofocus></ion-searchbar>
import { Component, ViewChild } from '@angular/core';
import { IonSearchbar } from '@ionic/angular';

  selector: 'app-home',
  templateUrl: '',
  styleUrls: [''],
export class HomePage {

  @ViewChild('autofocus', { static: false }) searchbar: IonSearchbar;

  constructor() { }

  ionViewWillEnter() {
    setTimeout(() => this.searchbar.setFocus(), 300);


We have completed our Ionic searchbar input focus. The ionic searchbars component represents a text field that can be used to search through a collection. They can be displayed inside of a toolbar or the main content.

Related posts

Spread the love

1 thought on “How to add and set ionic autofocus input”

Leave a Comment

Your email address will not be published.

Scroll to Top