import { Component, ViewChild} from \'@angular/core\';
import { Keyboard } from \'ionic-native\';
@Component({
templateUrl: \
Setting timeout worked for me!
setTimeout(() => {
this.inputToFocus.setFocus();
}, 800);
However, if a new input element is added it sets focus to first input only.
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!
You don't need to import the 'Input' from 'angular/core'.
Simply:
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);
}
}
And answering comment to Ciprian Mocanu:
It does not work in iOS :(
It works on iOS -> checked on iPhone 6 PLUS with iOS 10
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>
None of the above was working for me. Here is how I resolved:
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)
}
}
}
Then in your ion-input field just add the autofocus attribute:
<ion-input #input type="text" placeholder="..."
[(ngModel)]="myBoundVariable"
(keyup.enter)="myEnterKeyAction()"
autofocus></ion-input>
Tested on Browser and Android not IOS yet but no reason it should not work.
I found this solution to also fix the problem that the keyboard is pushing the content away.
<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();
});
}