Установите фокус на вход с помощью 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"
import {Component, ViewChild} from '@angular/core';
2) Создайте ссылку на свой вклад в свой шаблон html:
<ion-input #focusInput></ion-input>
3) Используйте @ViewChild, чтобы получить доступ к компоненту ввода, на который вы только что ссылались ранее.
@ViewChild('focusInput') myInput ;
4) Запуск фокуса
Используйте метод ionViewLoaded(), чтобы запускать его каждый раз при загрузке представления/страницы.
setTimeout не требуется
ionViewLoaded() {
setTimeout(() => {
Keyboard.show() // for android
this.myInput.setFocus();
},150); //a least 150ms.
}
4) Покажите клавиатуру на Android
import { Keyboard } from 'ionic-native';
Вызовите клавиатуру .show(), чтобы вызвать клавиатуру на Android.
5) Показать клавиатуру на iOS
добавьте эту строку в свой файл config.xml, чтобы она работала на iOS:
<preference name="KeyboardDisplayRequiresUserAction" value="false" />
С помощью великой статьи mhartington: http://mhartington.io/post/setting-input-focus/
Ответы
Ответ 1
Вам не нужно импортировать "Input" из "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);
}
}
И отвечая на комментарий к Киприану Мокану:
Это не работает в iOS :(
Работает на iOS → проверено на iPhone 6 PLUS с iOS 10
Ответ 2
Я думаю, вы должны сделать глобальную директиву для этого, поскольку вы, вероятно, захотите этого поведения более одного раза.
import { ViewChild, ElementRef, Directive, OnInit } from '@angular/core';
import { Keyboard } from 'ionic-native';
@Directive({
selector: '[autofocus]'
})
export class FocusInput implements OnInit {
@ViewChild('myinput') input
private focused: boolean
ngOnInit(){
this.focused = true
}
ionViewDidLoad() {
if (this.focused) {
setTimeout(()=>{
this.input.setFocus()
this.focused = false
Keyboard.show()
}, 300)
}
}
}
Теперь в поле ion-input
просто добавьте атрибут autofocus
<ion-input #myinput type="..." placeholder="..."
(keyup.enter)="someAction()"
autofocus ></ion-input>
Ответ 3
Никто из вышеперечисленных не работал у меня. Вот как я решил:
import { ElementRef, AfterViewChecked, Directive } from '@angular/core';
import {Keyboard} from 'ionic-native';
@Directive({
selector: '[autofocus]'
})
export class FocusInput implements AfterViewChecked {
private firstTime: boolean = true;
constructor(public elem: ElementRef) {
}
ngAfterViewChecked() {
if (this.firstTime) {
let vm = this;
setTimeout(function(){
vm.elem.nativeElement.firstChild.focus();
vm.firstTime = false;
Keyboard.show();
}, 300)
}
}
}
Затем в поле ввода ионов просто добавьте атрибут автофокуса:
<ion-input #input type="text" placeholder="..."
[(ngModel)]="myBoundVariable"
(keyup.enter)="myEnterKeyAction()"
autofocus></ion-input>
Протестировано в браузере и Android, но не в IOS, но без причины он не должен работать.
Ответ 4
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);
}
}
Ответ 5
import {Component,ViewChild} from '@angular/core';
import {NavController} from 'ionic-angular';
@Component({
templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
@ViewChild('myInput') myInput ;
constructor(private navCtrl: NavController) { }
ionViewDidLoad() {
window.setTimeout(() => {
this.myInput.setFocus();
}, 600); //SET A LONG TIME IF YOUR ARE IN A MODAL/ALERT
}
}
<ion-input #myInput ></ion-input>
Ответ 6
Я нашел это решение, чтобы устранить проблему, из-за которой клавиатура выталкивает контент.
<ion-list>
<ion-item>
<ion-label>Name</ion-label>
<ion-input #inputRef type="text"></ion-input>
</ion-item>
<button ion-button (click)="focusMyInput(inputRef)">Focus</button>
@ViewChild(Content) content: Content;
focusMyInput(inputRef) {
const itemTop = inputRef._elementRef.nativeElement.getBoundingClientRect().top;
const itemPositionY = this.content.scrollTop + itemTop -80;
this.content.scrollTo(null, itemPositionY, 500, () => {
inputRef.setFocus();
});
}
Ответ 7
В моем случае, по какой-то причине, ionViewLoaded() не запускался. Попробовал ionViewDidLoad() и установил таймер на 200, и он сработал.
150 оказалось слишком рано для меня. Полное решение:
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)
}
}
И на входном теге:
<ion-input type="text" #inputToFocus></ion-input>
Ответ 8
Для IOS и Android это нормально работает для меня. поместите код фокуса в ionViewWillEnter().
import { Component, ViewChild, ElementRef } from '@angular/core';
import { Keyboard } from '@ionic-native/keyboard';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
@ViewChild("Input") inputEl: ElementRef;
constructor(public keyboard:Keyboard){}
ionViewWillEnter() {
setTimeout(() => {
this.inputEl.nativeElement.focus();
this.keyboard.show();
}, 800); //If its your first page then larger time required
}
Входной тег в HTML файл
<ion-input type="text" #Input></ion-input>
И добавьте эту строку в ваш config.xml, чтобы он работал на iOS:
<preference name="KeyboardDisplayRequiresUserAction" value="false" />
Ответ 9
Если вам нужно установить фокус на вход в компоненте init, установите класс input-has-focus по умолчанию на ion-item, как показано ниже:
<ion-item class="input-has-focus">
Все это!
Ответ 10
я не думаю, что эта проблема была решена. я обнаружил, что этот пост прекрасно решил эту проблему: https://www.grzegorowski.com/ionic-3-framework-setfocus-of-an-input/
Ответ 11
Установка таймаута сработала у меня!
setTimeout(() => {
this.inputToFocus.setFocus();
}, 800);
Однако, если добавлен новый элемент ввода, он устанавливает фокус только на первый ввод.