I’m trying to figure out how to focus on ionic form inputs programatically on Ionic 4.
At first I tried to set focus on page init, by using @ViewChild , the Input class (that I believe is replacing the previous Text Input class) and ngAfterViewInit but I can’t make it work.
I tried the following:
HTML CODE:
<ion-input formControlName="email" #email></ion-input>
TS CODE:
export class LoginPage implements AfterViewInit {
@ViewChild('email') emailElement: Input;
ngAfterViewInit() {
this.emailElement.focus();
}
After many atempts, I could do a workaround by doing a setTimeout of 1 sec on th this.emailElement.focus() call
Has anyone had some experience on this topic?
1 Like
daerup
January 12, 2019, 10:08pm
#2
Have you found a solution?
No, I stopped working with Ionic-4 for a while until it’s ready
I managed to get this working with Ionic v4.11.0 doing something like this:
HTML CODE:
<ion-input #input></ion-input>
TS CODE:
export class LoginPage implements AfterViewInit {
@ViewChild('input') inputElement: IonInput;
ngAfterViewInit() {
setTimeout(() => {
this.inputElement.setFocus();
}, 400);
}
Note that I’m setting a timeout because the Input is in an <ion-modal>
so has to wait for the animation to finish. So it might not be needed if the input is on a normal page.
2 Likes
focus is in but the keyboard is not showing. Any solution on this?
on config
<preference name=“KeyboardDisplayRequiresUserAction” value=“false” />
in ionic 4 this one solved my problem
HTML CODE:
<ion-input #inputId></ion-input>
TS CODE:
import { Component, OnInit, ViewChild } from '@angular/core';
import { IonInput } from '@ionic/angular';
export class LoginPage implements OnInit {
@ViewChild('inputId', { static: false }) inputElement: IonInput;
ngAfterViewInit() {
setTimeout(() => {
this.inputElement.setFocus();
}, 400);
}
5 Likes
You can toggle the keyboard programmatically from the plugin.
Try using input native html
<input type="text" #user>
@ViewChild('user', { static: true }) user: ElementRef;
ngAfterViewInit(): void { this.user.nativeElement.focus(); }
1 Like
Thanks a lot, that’s worked!!
It works fine for me when I use the ionViewDidEnter lifecycle hook
ionViewDidEnter() {
this.inputElement.setFocus();
}
<ion-input formControlName=“title” required type=“text” #title>
{{title.setFocus()}}