import { Component, ViewChild} from \'@angular/core\';
import { Keyboard } from \'ionic-native\';
@Component({
templateUrl: \
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>
For IOS and Android its fine working for me. put focus code in 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
}
Input tag in html file
<ion-input type="text" #Input></ion-input>
And add this line to your config.xml to make it work on iOS :
<preference name="KeyboardDisplayRequiresUserAction" value="false" />
I think you should make a global directive for this as you will probably want this behavior more than once.
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)
}
}
}
Now on you ion-input
field just add the autofocus
attribute
<ion-input #myinput type="..." placeholder="..."
(keyup.enter)="someAction()"
autofocus ></ion-input>
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>