Setting Focus to an Input in Ionic

Hi everyone,

I would like to set the focus on an input at the initialization.

I have followed this great article : mhartington.io/post/setting-input-focus/ (which work great), but i want to do something slightly different by focusing at the initialization :

import { Component, ViewChild, ElementRef } from '@angular/core';

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {

  @ViewChild('input') myInput: ElementRef

  constructor() {}

  ngOnInit() {
    console.log("Init")
    this.myInput.setFocus();
  }

  focusInput(input) {
    input.setFocus();
  }
}

But i get the compiler error :

Property ‘setFocus()’ does not exist on ‘ElementRef’

Is “@ViewChild” appropriate for doing that ?

I tried with : @ViewChild('input') myInput: ElementRef

Am I misunderstanding something ? Do you have any ideas ?

Thanks a lot :slight_smile:

Can you use ‘autofocus’ in the HTML e.g.

Hope this helps

Amanda

Doesn’t work :confused:

SOLVED :

import {Component, Input, ViewChild} from '@angular/core';
import {NavController} from 'ionic-angular';

@Component({
  templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
  @ViewChild('input') myInput ;

  constructor(private navCtrl: NavController) { }

  ionViewLoaded() {

    setTimeout(() => {
      this.myInput.setFocus();
    },150);

 }

} 

1) import “Input”, “ViewChild” and “NavController”

import {Component, Input, ViewChild} from '@angular/core'; import {NavController} from 'ionic-angular';

2) Create a reference to your input in your template :

<ion-input #input>

@ViewChild('input') myInput ;

3) Trigger the focus

  ionViewLoaded() {

    setTimeout(() => {
      this.myInput.setFocus();
    },150);

 }

4) Show the keyboard

add this line to your config.xml :

<preference name="KeyboardDisplayRequiresUserAction" value="false" />

Hey!
Do you know how can i use your solution for dynamic generated inputs (with *ngFor) ?
i dont know how to set “#input” dynamically (so each one gets unique reference)

This doesn’t seem to be working for me. The focus sets correctly, and I have this line in my config.xml but it doesnt open keyboard. Could this be due to plugin ‘ionic-plugin-keyboard’?

On second look, it does work, but not on the first time focusing. I.e. after the first time the focus is set to the input

The same problem here. The focus sets correctly, but the keyboard doesn’t open. And I have the preference line on my config.xml.

I had this problem also. Not solved with this 4 steps.
The cursors is one moment on the inputfield, the keyboard raises and go back immediately, the cursors disappears also after that…

this way not works for me at all, I use code like this:

let element = this.elementRef.nativeElement.querySelector('input');
this.renderer.invokeElementMethod(element, 'focus', []);

where

private renderer: Renderer, private elementRef: ElementRef

in my constructor. This code allow to set focus on input element on a page.

I found this also http://blog.thecodecampus.de/ionic-2-set-focus-input-element/

This solution does not work for me… could you please provide a new solution?

Any other solutions for this? I tried all other threads as well, nothing worked :expressionless:

I am surprised they don’t focus by default when you click them this is standard behavior. Is it not for html inputs.

I need help on this too for multiple text boxes.

You can simply use this:

<ion-input #input type="text"></ion-input>
<button ion-button (click)="input.setFocus()">Focus</button>

Small addition to this: If you want to focus a field in a modal / alert or anything that requires a transition:
You have to set the setTimeout delay long enough for the transition to end! or else it will not focus.

Hello everyone!
I don’t know if any of you had this issue but after updating my project to Ionic 3.5.0 it seems like the focus and blur events are deprecated in ion-input.
these are the messages logged: “(focus) is deprecated in ion-input, use (ionFocus) instead” the same for blur.
I have a directive that makes use of the blur event so I can format the input values before send them to the server. I wouldn’t want to go input by input setting the ionBlur handler (my app is full of forms).

Does any of you would know how i could implement the ionBlur in my directive?

import { Directive, HostListener, ElementRef, Attribute} from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
	selector:'[inputFormat]'
})
export class InputFormat{
	elem:HTMLInputElement;

	constructor(
		public elRef:ElementRef, 
		public control:NgControl,
		@Attribute('inputFormat') public inputFormat:string){
		this.elem = elRef.nativeElement;
	}

	capitalize(input:String){
		let preps = ['de', 'di', 'do', 'da', 'dos', 'das', 'dello', 'della', 'dalla', 'dal', 'del', 'e', 'em', 'na', 'no', 'nas', 'nos', 'van', 'von', 'y'];
	    let str = input.replace(/(^|\s)([a-z])/g, function(m, p1, p2) {
	        return p1 + p2.toUpperCase();
	    });
	    //console.log(str);
	    let arr = str.split(" ");
	    //console.log(arr);	    
	    for(let i = 0; i<arr.length; i++){
	        let istr = arr[i];
	        for(let j in preps){
	            if(istr.toLowerCase() == preps[j]){
	                arr[i] = preps[j];
	            }
	        }
	    }	    
	    str = arr.join(' ');
	    return str;
	}

	@HostListener('focus', ['$event.target.value'])
	onFocus(value){}

	@HostListener('blur', ['$event.target.value'])
	onBlur(value){
		if(value != undefined && value != ''){		
			if(this.inputFormat == 'lowercase'){
				this.control.control.setValue(value.toLowerCase());
			}
			else if(this.inputFormat == 'uppercase'){
				this.control.control.setValue(value.toUpperCase());
			}
			else if(this.inputFormat == 'capitalize'){
				let val = this.capitalize(value.toLowerCase());
				this.control.control.setValue(val);
			}
		}		
	}
	
}

My system infos:

global packages:

    @ionic/cli-utils : 1.4.0
    Cordova CLI      : 7.0.1 
    Ionic CLI        : 3.4.0

local packages:

    @ionic/app-scripts              : 1.3.12
    @ionic/cli-plugin-cordova       : 1.4.0
    @ionic/cli-plugin-ionic-angular : 1.3.1
    Cordova Platforms               : ios 4.3.1
    Ionic Framework                 : ionic-angular 3.5.0

System:

    Node       : v6.5.0
    OS         : OS X El Capitan
    Xcode      : Xcode 8.1 Build version 8B62 
    ios-deploy : 1.9.1 
    ios-sim    : 5.0.13 
    npm        : 3.10.3 

thanks a lot!!

Btw, waiting for transitions to end by setting a delay long enough is kinda crappy. Does anyone know if theres any hooks, callbacks or observables for transitions?

I think Alerts, Modals and such have a dismiss method and they return an Observable dont they? You could go from there!

Take a look at this: Dismissing And Async Navigation here: http://ionicframework.com/docs/api/components/alert/AlertController/

they have, but sometimes the usecase is more compicated than that.
For instance: I have a button, which requires a user to be logged in, but he can click it always.
If not loggedIn a modal with the loginpage opens.
Logging in will lead to the removal of the modal (from within the modal)
Now on the underlying page stuff has changes, and the ion-content needs to resize. To properly do this i need to wait unit the transition is over.

I will check if there is an observable for the open - close events, but I doubt whether they take the transition time into account.

But the navTransition looks promising!

mmmm what about the profileModal.onDidDismiss
look at this:

import { Component } from '@angular/core';
import { ModalController, ViewController } from 'ionic-angular';

@Component(...)
class HomePage {

 constructor(public modalCtrl: ModalController) {

 }

 presentContactModal() {
   let contactModal = this.modalCtrl.create(ContactUs);
   contactModal.present();
 }

 presentProfileModal() {
   let profileModal = this.modalCtrl.create(Profile, { userId: 8675309 });
   profileModal.onDidDismiss(data => {
     console.log(data);
   });
   profileModal.present();
 }

}

@Component(...)
class Profile {

 constructor(public viewCtrl: ViewController) {

 }

 dismiss() {
   let data = { 'foo': 'bar' };
   this.viewCtrl.dismiss(data);
 }

}

here: http://ionicframework.com/docs/api/components/modal/ModalController/