使用 Ionic 2 将焦点设置在输入上 [英] Set focus on an input with Ionic 2
问题描述
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) 导入ViewChild"
从 '@angular/core' 导入 {Component, ViewChild};
2) 在您的 html 模板中创建对您的输入的引用:
<ion-input #focusInput></ion-input>
3) 使用@ViewChild 访问您刚才引用的输入组件.
@ViewChild('focusInput') myInput ;
4) 触发焦点
每次加载视图/页面时使用 ionViewLoaded() 方法触发它.
Use the ionViewLoaded() method to trigger it each time the view/page is loaded.
需要setTimeout
ionViewLoaded() {
setTimeout(() => {
Keyboard.show() // for android
this.myInput.setFocus();
},150); //a least 150ms.
}
4) 在 Android 上显示键盘
从 'ionic-native' 导入 { Keyboard };
调用 Keyboard.show() 在 Android 上调用键盘.
Call Keyboard.show() to call the keyboard on Android.
5) 在 iOS 上显示键盘
将此行添加到您的 config.xml 以使其在 iOS 上运行:
add this line to your config.xml to make it work on iOS :
<preference name="KeyboardDisplayRequiresUserAction" value="false"/>
借助 mhartington 的精彩文章:http://mhartington.io/post/setting-input-focus/
推荐答案
你不需要从'angular/core'导入'Input'.
You don't need to import the 'Input' from 'angular/core'.
简单地说:
import {Component,ViewChild} from '@angular/core';
import {NavController, TextInput } from 'ionic-angular';
@Component({
templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
@ViewChild('input') myInput: TextInput;
constructor(private navCtrl: NavController) { }
ionViewDidLoad() {
setTimeout(() => {
this.myInput.setFocus();
},150);
}
}
并回答 Ciprian Mocanu 的评论:
And answering comment to Ciprian Mocanu:
它在 iOS 中不起作用:(
It does not work in iOS :(
它适用于 iOS -> 在带有 iOS 10 的 iPhone 6 PLUS 上检查
It works on iOS -> checked on iPhone 6 PLUS with iOS 10
这篇关于使用 Ionic 2 将焦点设置在输入上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!