メインコンテンツまでスキップ
バージョン: v7

Managing Focus

Ionic provides a setFocus API on components such as Input, Searchbar, and Textarea that allows developers to manually set focus to an element. This API should be used in place of the autofocus attribute and called within:

  • The ionViewDidEnter lifecycle event for routing applications when a page is entered.
  • The didPresent lifecycle event for overlays when an overlay is presented.
  • The appload event for vanilla JavaScript applications when the application loads.
  • The result of a user gesture or interaction.

Why not autofocus?

The autofocus attribute is a standard HTML attribute that allows developers to set focus to an element when a page loads. This attribute is commonly used to set focus to the first input element on a page. However, the autofocus attribute can cause issues in routing applications when navigating between pages. This is because the autofocus attribute will set focus to the element when the page loads, but will not set focus to the element when the page is revisited. Learn more about the autofocus attribute in the MDN Web Docs.

Platform Restrictions

There are platform restrictions you should be aware of when using the setFocus API, including:

  1. Android requires user interaction before setting focus to an element. This can be as simple as a user tapping on the screen.
  2. Interactive elements can only focused a result of a user gesture on Mobile Safari (iOS), such as calling setFocus as the result of a button click.

Basic Usage

The example below demonstrates how to use the setFocus API to request focus on an input when the user clicks a button.

Routing

Developers can use the ionViewDidEnter lifecycle event to set focus to an element when a page is entered.

/* example.component.ts */
import { Component, ViewChild } from '@angular/core';
import { IonInput } from '@ionic/angular';

@Component({
selector: 'app-example',
templateUrl: './example.component.html',
})
export class ExampleComponent {
@ViewChild('input') input!: IonInput;

ionViewDidEnter() {
this.input.setFocus();
}
}

Overlays

Developers can use the didPresent lifecycle event to set focus to an element when an overlay is presented.

<ion-modal>
<ion-input></ion-input>
</ion-modal>

<script>
const modal = document.querySelector('ion-modal');
modal.addEventListener('didPresent', () => {
const input = modal.querySelector('ion-input');
input.setFocus();
});
</script>