Set focus on an input with Ionic 2

Solution 1:

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

Solution 2:

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>

Solution 3:

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.

Solution 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);

 }

}

Create a reference to your input in your template :

<ion-input #Comment>