Set focus on an input with Ionic 2

2019-01-22 17:22发布

SOLVED :

import { Component, ViewChild} from '@angular/core';
import { Keyboard } from 'ionic-native';


@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  @ViewChild('input') myInput ;

  constructor() {}

  ionViewDidLoad() {

    setTimeout(() => {
      Keyboard.show() // for android
      this.myInput.setFocus();
    },150);

 }

} 

1) import "ViewChild"

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

2) Create a reference to your input in your html template :

<ion-input #focusInput></ion-input>

3) Use @ViewChild to get access to the input component you just referenced previously.

@ViewChild('focusInput') myInput ;

4) Trigger the focus

Use the ionViewLoaded() method to trigger it each time the view/page is loaded.

setTimeout is needed

  ionViewLoaded() {

    setTimeout(() => {
      Keyboard.show() // for android
      this.myInput.setFocus();
    },150); //a least 150ms.

 }

4) Show the keyboard on Android

import { Keyboard } from 'ionic-native';

Call Keyboard.show() to call the keyboard on Android.

5) Show the keyboard on iOS

add this line to your config.xml to make it work on iOS :

<preference name="KeyboardDisplayRequiresUserAction" value="false" />

With the help from the great article of mhartington : http://mhartington.io/post/setting-input-focus/

9条回答
仙女界的扛把子
2楼-- · 2019-01-22 17:55

If you need to set focus on an input at init component, set the class input-has-focus by default to ion-item just like this:

<ion-item class="input-has-focus">

That's all!

查看更多
Rolldiameter
3楼-- · 2019-01-22 18:00

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

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  @ViewChild('Comment') myInput ;

  constructor(private navCtrl: NavController) { }

  ionViewLoaded() {

    setTimeout(() => {
      this.myInput.setFocus();
    },150);

 }

}

Create a reference to your input in your template :

<ion-input #Comment>

查看更多
乱世女痞
4楼-- · 2019-01-22 18:00

In my case, for some reason, ionViewLoaded() was not getting triggered. Tried ionViewDidLoad() and set the timer to 200 and it worked.

150 proved too early for me. Complete Solution:

import { Component, ViewChild } from '@angular/core';//No need to import Input

export class HomePage {

  @ViewChild('inputToFocus') inputToFocus;
  constructor(public navCtrl: NavController) {}

  ionViewDidLoad()
  {
    setTimeout(() => {
      this.inputToFocus.setFocus();
    },200)
  }  
}

And on the input tag:

<ion-input type="text" #inputToFocus></ion-input>
查看更多
登录 后发表回答