Setting Focus to an Input in Ionic


#20

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!


#21

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/


#22

Cool, Im gonna look into that, hoping that will take the animation time into acount. thnx, will post what I find here for reference


#23

Yup, thats what i just thought! whether the event is fired before, during or after the transition! let us know!!
cheers!


#24

Did you manage to find the solution?


#25

hi, I am using ionic 3… I tried both solutions but it didn’t work, any advice ! thanx … the element ref method shows error cannot read property 'focus' of null TypeError


#26

For people using WKWebView and having the focus issue, take a look at https://www.npmjs.com/package/cordova-plugin-wkwebview-inputfocusfix.


#27

Thanks friend for your help its work to me


#28

yes it didn’t work for me. I also get this error cannot read property ‘focus’ of null TypeError


#29

There is NavController.isTransitioning(), not really a callback, but can be checked and used to delay actions until a transition is complete. In my experience though (Ionic 3.6.1), the setTimeout is required for setting input focus, but can use a 0 millisecond delay (which is the default if omitted). As I understand it, this is needed to queue an operation and trigger Angular change detection. I put it inside an ionViewDidEnter hook. There are also some Angular Lifecycle Hooks available, which might be more appropriate in certain cases.


#30

after that how do I move focus to next elemnt,sine the cursor is stuck there!


#31

I found this possible solution:

.html

<ion-content>
  <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>
  </ion-list>
</ion-content>

.ts

import {Content} from 'ionic-angular';

@ViewChild(Content) content: Content;

  focusMyInput(inputRef) {

    let itemTop = inputRef._elementRef.nativeElement.getBoundingClientRect().top;
    let itemPositionY = this.content.getContentDimensions().scrollTop + itemTop -80;
   
    this.content.scrollTo(null, itemPositionY, 500, () => {
      inputRef.setFocus();
    });

  }

But you have to make sure you have enough space to scroll at bottom. Tested on iOS 11


#32

Content is not defined error


#33

Make sure to “import {Content} from ‘ionic-angular’;” at the top of your .ts file. And of course your content musst be placed between tags.

I’ve edited my post.


#34

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>


#35

The best solution. Works great for me too! =) But in my case I used set.Blur() method for my own purposes.


#36

I found a solution as a Directive

import { Directive, Renderer, ElementRef} from '@angular/core';
 
@Directive({ 
    selector: '[focuser]' // Attribute selector
})
export class Focuser {

    constructor(private renderer:Renderer,
                private elementRef:ElementRef) {
    }

    ngAfterViewInit() { 
        // we need to delay our call in order to work with ionic ...
        setTimeout(() => {
            const element = this.elementRef.nativeElement.querySelector('input');
            this.renderer.invokeElementMethod(element, 'focus', []);
        }, 1000);
    }   
}

add to app.module

import { Focuser } from "../directives/focuser/focuser";

@NgModule({
  declarations: [ ... 
                         Focuser  ]

use the directive.

<ion-input focuser . . . >


#37

Does it work in mobile iOS safari?


#38

Make sure to upload : cordova-plugin-ionic-webview


#39

Hey Blaydator,
I am having the same issue here and couldn’t make input field focus on iPhone (Keyboard doesn’t appear too). Do you have a solution on this?